Reading File Using Java
Reading File Using Java, in this article i will step through the sample code and show you how to read the content contain inside a file.
The Sample Code.
Refer the below for the Sample Code
package fileHandling; import java.io.File; import java.util.Scanner ; import java.io.FileNotFoundException; public class readTheFile { public static void main(String[] args)throws FileNotFoundException { // TODO Auto-generated method stub String fileName ="c:/users/user/anotherFile.txt"; File thisNewFile =new File(fileName); Scanner rfile = new Scanner(thisNewFile); while(rfile.hasNextLine()){ String line = rfile.nextLine(); System.out.println(line); } rfile.close(); } }
How it works.
- First you will need to import the libraries ” java.io.File , java.util.Scanner,java.io.FileNotFoundException “
- Open “c:/users/user/anotherFile.txt” and assign the file content into a String Variable called “fileName”
- Create a new “File ” Object called” thisNewFile” and assign as an argument into the File
- Create a new Scanner Object called”rfile” and assign the “thisNewFile” instance into the new created “rfile” scanner object
- Use the “hasNextLine() “command to loop through the content inside the “rfile” , print out the content if detected
Reading File Using Exception
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class App { public static void main(String[] args) { // Create a new Object " newFile " to read the File " testFile " File newfile = new File("testFile.txt"); // At the Initial Stage "lineRead " Line being read equal null BufferedReader lineRead = null; // try to read the file try { // Instantiate new "fileRead" object , and pass in the" newfile" instant FileReader fileRead = new FileReader(newfile); // "lineRead " Assign the Value read through "BufferReader() " into lineRead lineRead = new BufferedReader(fileRead); // Loop through the File to check whether every single line is read // While line not equal to nothing ( null ) Continue reading and print out the Result String line; while( (line = lineRead.readLine()) != null ) { System.out.println(line); } // Catch the File Not Found Exception } catch (FileNotFoundException e) { System.out.println("File not found: " + newfile.toString()); // Catch the Unable to read file Exception } catch (IOException e) { System.out.println("Unable to read file: " + newfile.toString()); } // Catch the Unable to close file Exception finally { try { lineRead.close(); } catch (IOException e) { System.out.println("Unable to close file: " + newfile.toString()); } catch(NullPointerException ex) { // } } } }
Check out Generic Type Object in Java here