How do I read a text file?
Category: java.io, viewed: 8849 time(s).
The code shown below is an example how to read a text file. This program will read a file called test.txt and shown its content.
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileNotFoundException; import java.io.IOException; public class ReadTextFileExample { public static void main(String[] args) { File file = new File("test.txt"); StringBuffer contents = new StringBuffer(); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String text = null; // repeat until all lines is read while ((text = reader.readLine()) != null) { contents.append(text) .append(System.getProperty( "line.separator")); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { e.printStackTrace(); } } // show file contents here System.out.println(contents.toString()); } } |
Related Examples
- How do I store properties as XML file?
- How do I load properties from XML file?
- How do I convert InputStream to String?
- How do I convert string into InputStream?
- How do I get an exception stack trace message?
- How do I use Console class to read user input?
- How do I store objects in file?
- How do I use DataInputStream and DataOutputStream?
- How do I use RandomAccessFile class?
- How do I create a directories recursively?
|
|