Java Examples - Read a file
Advertisements
Problem Description
How to read a file ?
Solution
This example shows how to read a file using readLine method of BufferedReader class.
import java.io.*; public class Main { public static void main(String[] args) { try { BufferedReader in = new BufferedReader(new FileReader("c:\\filename")); String str; while ((str = in.readLine()) != null) { System.out.println(str); } System.out.println(str); } catch (IOException e) { } } }
Result
The above code sample will produce the following result.
aString
The following is another sample example of read a file in Java
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class BufferedReaderExample { public static void main(String[] args) { try (BufferedReader br = new BufferedReader( new FileReader("C:\\\\Users\\\\TutorialsPoint7\\\\Desktop\\\\bbc.txt"))) { String sCurrentLine; while ((sCurrentLine = br.readLine()) != null) { System.out.println(sCurrentLine); } } catch (IOException e) { e.printStackTrace(); } } }
The above code sample will produce the following result.
BUILD SUCCESSFUL
java_files.htm
Advertisements