File Write

The following static methods can be used to easily write text into a file. Different arguments allow a flexible call with path string, file object or file stream.

Path String

The path method expects for the first argument the file path as string. If the file already exists the content will be replaced by the new data.

public static void write(String path, String text, String charsetName) throws IOException { write(new FileOutputStream(path), text, charsetName); }

File Object

The file method gets the file path in a file object. This method also overwrites existing data.

public static void write(File file, String text, String charsetName) throws IOException { write(new FileOutputStream(file), text, charsetName); }

File Stream

The ultimate method for saving data to the file expects for the first argument a file stream. All appearing exceptions will be outreach to the outside and thus can either be catch directly in the calling method or in a global exception routine.

public static void write(OutputStream outputStream, String text, String charsetName) throws IOException { BufferedWriter bufferedWriter = null; OutputStreamWriter outputWriter = null; try { outputWriter = new OutputStreamWriter(outputStream, charsetName); bufferedWriter = new BufferedWriter(outputWriter); bufferedWriter.write(text, 0, text.length()); bufferedWriter.flush(); } finally { if (bufferedWriter != null) bufferedWriter.close(); if (outputWriter != null) outputWriter.close(); if (outputStream != null) outputStream.close(); } }


write("test.txt", "test content", "utf-8"); write(file, "test content", "utf-8"); write(stream, "test content", "utf-8");


Johannes Hammoud File Write 21.08.2009

I Coding : Community about Java programing

Language German+-

Java JSF JavaScript HTML CSS NetBeans GlassFish MySQL