Reading files in Java

I am going to show example which shows how to read a file in Java.
If you want to read some file you should start with FileInputStream. This class is a concrete subclass of InputStream. It provides an input stream connected to a particular file.
Example:

package tutorial;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintStream;

/**
 * This class shows how to read a file and show it in system console
 * @author The Developer's Info
 */
public class Main {

    public static void main(String[] args) {
        FileInputStream fileInputStream = null;
        try {
            String workingDirectory = System.getProperty("user.dir");
            File fileDir = new File(workingDirectory, "src/tutorial");
            File file = new File(fileDir, "Main.java");

            fileInputStream = new FileInputStream(file);

            show(fileInputStream, System.out);
        } catch (IOException ex) {
        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
            } catch (IOException ex) {}
        }
        System.out.println();
    }

    /**
     * This method shows Main.java content in console
     * @param fin input stream
     * @param out output stream
     * @throws IOException
     */
    private static void show(FileInputStream fin, PrintStream out) throws IOException {
        byte[] buffer = new byte[1024];
        while (true) {
            int bytesRead = fin.read(buffer);
            if (bytesRead == -1) {
                break;
            }
            out.write(buffer, 0, bytesRead);
        }
    }
}

Main method here is show(). It is very simple method. In general Java allows to work with all things very easy.

  • Share/Bookmark

Related posts:

  1. Writing files in Java
  2. Using buffered streams in Java
  3. Using InputStream in Java
  4. Using PushBackInputStream in Java
  5. Multitargeting output streams in Java

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>