A text file is created using Java with the File Object and an OutputStream.
Writer out = new BufferedWriter( new OutputStreamWriter( new FileOutputStream(file), "UTF-8")); out.write(lines); out.close();
This example creates a file using the File Object. Then it creates a Writer from an OutputStreamWriter setting the encoding to utf8. The content of the file is then written and the writer is closed.
import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; public class FileCreate { public static void main(String[] argv) { File file = new File("V:/tmp/test2.txt"); String lines = "Content of the file"; Writer out = null; try { out = new BufferedWriter( new OutputStreamWriter( new FileOutputStream(file), "UTF-8")); out.write(lines); } catch (IOException e) { e.printStackTrace(); }finally{ if( out != null ) try { out.close(); } catch (IOException e) { e.printStackTrace(); } } System.out.println("The file has been created."); } }
The file has been created.
When creating the OutputStreamWriter, it is important to pass, as a parameter, the encoding of the file that is being created. This ensures that the right encoding is used, and does not allow uncertainty. It is very important when writing unicode characters, this way no badly encoded charaters are written in the file.
The writer is created outside the main try catch block. This way we can use a finally block to ensure that the writer is closed. If the writer would be defined in the try block and closed at the end before the catch, we would not have a way to sure that that write is closed at the end of the process.