Java file handling tutorial - Reading from a file
Home - Tutorials - File handling
This tutorial demonstrates you the basic Java file handling concepts with code examples.
Tutorial info:
| Name: | Java file handling tutorial |
| Total steps: | 2 |
| Category: | File handling |
| Date: | 2009-04-27 |
| Level: | Beginner |
| Product: | See complete product |
| Viewed: | 30089 |
Bookmark Java file handling tutorial
Step 2 - Reading from a file
Java file handling tutorial
If everything is alright, you have successfully written some basic text into a file. Now it's time to read the file content back. Not surprisingly reading from a file is very similar to writing. We only need to use *Reader objects instead of *Writer objects. It means that you can use FileReader or BufferedReader. As a simple FileReader can handle only a single character or a character array it is more convenient to use the BufferedReader which can read a complete line from a file as a string. So using a BufferedReader we can read a text file line by line with the readln() method as you can see in this example:
Code:
I hope this article made a beginner java programmer life easier. Finally let's see how the complete Java program looks like:
Code:
public class FileDemo { FileDemo fd = new FileDemo(); fd.writeFile(); } public void writeFile() { String fileName = "c:\\test.txt"; try { writer.write("Test text."); writer.newLine(); writer.write("Line2"); writer.close(); e.printStackTrace(); } } String fileName = "c:\\test.txt"; try { String line; while ((line = reader.readLine()) != null) { fileContent.append(line).append(LS); } e.printStackTrace(); } return fileContent.toString(); } }
Previous Step of Java file handling tutorial
Tags: java file handling tutorial, java file handling, file handling tutorial, java, file
| Java file handling tutorial - Table of contents |
|---|
| Step 1 - Java file handling basics |
| Step 2 - Reading from a file |