Java “file write” (or “file save”) methods

Java write/save FAQ: Can you share an example of how to write to a file in Java?

Sure. Here are two "Java file save" or "Java file write" examples, taken from my Java file utilities article (Java file utilities to write, save, open, read, and copy files). I'm not going to explain these too much, but if you need a simple method to write to a file in your Java programs, I hope these methods will help you.

1) A Java "save file as text" example

This first Java method lets you write plain text (a String) to a file:

/**
 * Save the given text to the given filename.
 * @param canonicalFilename Like /Users/al/foo/bar.txt
 * @param text All the text you want to save to the file as one String.
 * @throws IOException
 */
public static void writeFile(String canonicalFilename, String text) 
throws IOException
{
  File file = new File (canonicalFilename);
  BufferedWriter out = new BufferedWriter(new FileWriter(file)); 
  out.write(text);
  out.close();
}

2) A Java save/write binary data to file example

This second Java file-writing method lets you write an array of bytes to a file in Java (binary data), using the FileOutputStream and BufferedOutputStream classes:

/**
 * Write an array of bytes to a file. Presumably this is binary data; for plain text
 * use the writeFile method.
 */
public static void writeFileAsBytes(String fullPath, byte[] bytes) throws IOException
{
  OutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(fullPath));
  InputStream inputStream = new ByteArrayInputStream(bytes);
  int token = -1;

  while((token = inputStream.read()) != -1)
  {
    bufferedOutputStream.write(token);
  }
  bufferedOutputStream.flush();
  bufferedOutputStream.close();
  inputStream.close();
}

That method can be good if you want to write binary data to a file using Java.

I hope these "Java file write" example methods will help in your own Java file programming needs.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.