+92 332 4229 857 99ProjectIdeas@Gmail.com

How To Read/Write In File In Java


How to read/write in file:
The following code shows you the way to write a data in file and how to read data from file.



Code

Creating File:

import
java.io.*; // package For writing/reading/creating files

try {

    FileWriter fw = new FileWriter(new File("NewFile.txt"));
    fw.close();

 } catch (IOException e) {
   e.printStackTrace();
}


Write in file:

try {
   FileWriter fw = new FileWriter(new File("NewFile.txt"),true); // "true" means to append data in file, if you don't write "true" then every time you write in that particular file it will overwrite the data
   fw.write("I Am Dangerous");
   fw.close();
} catch (IOException e) {
      e.printStackTrace();
}


Read From File:

try {
      FileReader fr = new FileReader(new File("NewFile.txt"));
      BufferedReader br = new BufferedReader(fr);
      String line = br.readLine();

      while(line != null) {

            System.out.println(line);
            line = br.readLine();
      }

      br.close();
      fr.close();

} catch (FileNotFoundException fex) {

      fex.printStackTrace();

} catch (IOException ioEx) {

      ioEx.printStackTrace();
}

Note: if you don't write the file accessing code (reading/writing) in try catch block then the compiler wont let you even compile the program unless you write in try catch block. Likewise same as when taking input from console, we also write that code in try catch block.

0 comments: