Difference between revisions of "Reading a text file"
From MyWiki
(3 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
+ | '''Link''' http://tutorials.jenkov.com/java-io/file.html#instantiating-a-java-io-file <br> | ||
+ | '''The File class''' | ||
+ | <source lang="java"> | ||
+ | File file = new File("c:\\data\\input-file.txt"); | ||
+ | </source> | ||
+ | '''Example''' | ||
+ | |||
<source lang="java"> | <source lang="java"> | ||
BufferedReader br = new BufferedReader(new FileReader(file)); | BufferedReader br = new BufferedReader(new FileReader(file)); | ||
Line 7: | Line 14: | ||
br.close(); | br.close(); | ||
+ | </source> | ||
+ | |||
+ | '''Another example'''<br> | ||
+ | <source lang="java"> | ||
+ | import java.io.*; | ||
+ | class FileRead | ||
+ | { | ||
+ | public static void main(String args[]) | ||
+ | { | ||
+ | try{ | ||
+ | // Open the file that is the first | ||
+ | // command line parameter | ||
+ | FileInputStream fstream = new FileInputStream("textfile.txt"); | ||
+ | // Get the object of DataInputStream | ||
+ | DataInputStream in = new DataInputStream(fstream); | ||
+ | BufferedReader br = new BufferedReader(new InputStreamReader(in)); | ||
+ | String strLine; | ||
+ | //Read File Line By Line | ||
+ | while ((strLine = br.readLine()) != null) { | ||
+ | // Print the content on the console | ||
+ | System.out.println (strLine); | ||
+ | } | ||
+ | //Close the input stream | ||
+ | in.close(); | ||
+ | }catch (Exception e){//Catch exception if any | ||
+ | System.err.println("Error: " + e.getMessage()); | ||
+ | } | ||
+ | } | ||
+ | } | ||
</source> | </source> |
Latest revision as of 10:17, 17 September 2014
Link http://tutorials.jenkov.com/java-io/file.html#instantiating-a-java-io-file
The File class
File file = new File("c:\\data\\input-file.txt");
Example
BufferedReader br = new BufferedReader(new FileReader(file)); String line; while ((line = br.readLine()) != null) { // process the line. } br.close();
Another example
import java.io.*; class FileRead { public static void main(String args[]) { try{ // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream("textfile.txt"); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; //Read File Line By Line while ((strLine = br.readLine()) != null) { // Print the content on the console System.out.println (strLine); } //Close the input stream in.close(); }catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } } }