Java: Writing a Text File with a Code Page
This short piece of code demonstrates how to write a text file in Java and setting a code page. The PrinterWriter class contains a number of methods for outputting text to a file. The OutputStreamWriter class specifies the code page for the text file. The PrinterWriter class wraps this class. In turn, the OutputStreamWriter class wraps a FileOutputStream class which creates the handle to an actual file.
Download source for: WriteTextCodePage.java
1:/** Simple Program to write a text file 2:*/ 3: 4:import java.io.*; 5: 6:public class WriteTextCodePage{ 7: public static void main(String[] args){ 8: try { 9: FileOutputStream outFile = new FileOutputStream(args[0]); 10: OutputStreamWriter outStream = new OutputStreamWriter(outFile,"UTF-8"); 11: PrintWriter out = new PrintWriter(outFile); 12: 13: // Also could be written as follows on one line 14: // Printwriter out = new PrintWriter(new OutputStreamWrite(outFile)); 15: 16: // Write text to file 17: out.println("This is line 1"); 18: out.println("This is line 2"); 19: out.print("This is line3 part 1, "); 20: out.println("this is line 3 part 2"); 21: out.close(); 22: } catch (IOException e){ 23: e.printStackTrace(); 24: } 25: } 26:}