Sunday, 20 January 2013

File handling : Creating ,Reading ,Writing Text files

Code:

public class CreatingReadingWritingTextFiles {

public static void main(String[] args) throws IOException {
// creating
File f = new File("C:\\temp.txt");
f.createNewFile();
// writing
FileWriter w = new FileWriter("C:\\temp.txt");
BufferedWriter out = new BufferedWriter(w);
out.write("hello we are writing in a file");
out.newLine();
out.write("This is a new line");
out.flush();
//reading
FileReader r = new FileReader("C:\\temp.txt");
BufferedReader bfr = new BufferedReader(r);
String x ="";
//System.out.println(bfr.readLine());
//System.out.println(bfr.readLine());
//System.out.println(bfr.readLine());
while((x = bfr.readLine()) != null){
System.out.println(x);
}
}

}

4 comments:

  1. this is not creating text file. it is giving me errors as

    Exception in thread "main" java.io.IOException: Access is denied
    at java.io.WinNTFileSystem.createFileExclusively(Native Method)
    at java.io.File.createNewFile(Unknown Source)
    at readWrite.CreatingReadingWritingTextFiles.main(CreatingReadingWritingTextFiles.java:10)

    ReplyDelete
    Replies
    1. Hi I think u r creating directly in C drive
      Try Creating in other folders like documents or other drives in your computer

      Delete
  2. Nice Article. Very Helpful. You can follow this article also Java File handling tutorials with examples

    http://www.javaproficiency.com/2015/02/file-handling-in-java.html

    ReplyDelete
  3. Thanks for sharing nice article . It's very help visit File Handling In Java

    ReplyDelete