File Read

The following static methods can be used to easily read text from a file. Different arguments allow a flexible call with path string, file object or file stream.

Path String

The path method expects for the first argument the file path as string.

public static String read(String path, String charsetName) throws FileNotFoundException, bIOException { return read(new FileInputStream(path), charsetName); }

File Object

The file method gets the file path in a file object.

public static String read(File file, String charsetName) throws FileNotFoundException, IOException { return read(new FileInputStream(file), charsetName); }

File Stream

The ultimate method for reading data from the file expects for the first argument a file stream. All appearing exceptions will be outreach to the outside and thus can either be catch directly in the calling method or in a global exception routine.

public static String read(InputStream inputStream, String charsetName) throws IOException { int c; BufferedReader bufferReader = null; InputStreamReader inputReader = null; StringBuilder content = new StringBuilder(); try { inputReader = new InputStreamReader(inputStream, charsetName); bufferReader = new BufferedReader(inputReader); while ((c = bufferReader.read()) != -1) content.append( (char) c ); } finally { if (bufferReader != null) bufferReader.close(); if (inputReader != null) inputReader.close(); if (inputStream != null) inputStream.close(); } return content.toString(); }

Call

read("test.txt", "utf-8"); read(file, "utf-8"); read(stream, "utf-8");

Resources

Johannes Hammoud File Read 06.09.2009

I Coding : Community about Java programing

Language German+-

Java JSF JavaScript HTML CSS NetBeans GlassFish MySQL

Imprint

Visits
6279973
Today
7295