This short piece of code demonstrates how to write a text file in
Java. The PrinterWriter class contains a number of methods for
outputting text to a file. The FileWriter class is a convenience class
for writing to a text file. It uses the default code page for the
operating environment your virtual machine is running in. If you need to
specify a specific code page, then you must use the OutputStreamWriter
class instead.
1:/** Simple Program to write a text file 2:*/ 3: 4: import java.io.*; 5: 6: public class WriteText{ 7: public static void main(String[] args){ 8: try { 9: FileWriter outFile = new FileWriter(args[0]); 10: PrintWriter out = new PrintWriter(outFile); 11: 12: // Also could be written as follows on one line 13: // Printwriter out = new PrintWriter(new FileWriter(args[0])); 14: 15: // Write text to file 16: out.println("This is line 1"); 17: out.println("This is line 2"); 18: out.print("This is line3 part 1, "); 19: out.println("this is line 3 part 2"); 20: out.close(); 21: } catch (IOException e){ 22: e.printStackTrace(); 23: } 24: } 25: }
No comments:
Post a Comment