04-24-2011, 10:10 PM
Code:
println() prints and moves cursor to next line, you can run and check this behavior.
import java.io.*;
public class WriteFileEx {
public static void main (String args[ ]) {
FileWriter fw = null;
PrintWriter pw = null;
try {
// attaching node stream with data source
// if file does not exist, it automatically creates it
fw = new FileWriter ("output.txt");
// attatching filter stream over node stream
pw = new PrintWriter(fw);
String s1 = "Hello World";
String s2 = "Web 2 Design and Development";
// writing first string to file
pw.println(s1);
// writing second string to file
pw.println(s2);
// flushing stream
pw.flush();
// closing streams
pw.close();
fw.close();
}catch(IOException ioex){
System.out.println(ioex);
}
} // end main
} // end class
If you are running your code again previous data in the file will be overwritten. To
You need to open the file in append mode, other wise data will be overwritten each time you will run your code.
For this you will also pass 2nd argument true while creating the FileWriter object
fw = new FileWriter ("output.txt", true);
Here is the complete code.
import java.io.*;
public class WriteFileEx {
public static void main (String args[ ]) {
FileWriter fw = null;
PrintWriter pw = null;
try {
// attaching node stream with data source
// if file does not exist, it automatically creates it
fw = new FileWriter ("output.txt", true);
// attatching filter stream over node stream
pw = new PrintWriter(fw);
String s1 = "Hello World";
String s2 = "Web 2 Design and Development";
// writing first string to file
pw.println(s1);
// writing second string to file
pw.println(s2);
// flushing stream
pw.flush();
// closing streams
pw.close();
fw.close();
}catch(IOException ioex){
System.out.println(ioex);
}
} // end main
} // end class
