How to write a String to a File in java

There are situations when we need to write a string to a file. Common example is for creating logs, if we are not using any logging framework. There are various ways of doing this. Below are listed some common methods.

Method 1: Using java.io.BufferedWriter

	static void writeUsingBufferedWriter(String outFilePath, String stringToWrite)
		BufferedWriter bwr = null;
		try {
			bwr = new BufferedWriter(new FileWriter(outFilePath));
			bwr.write(stringToWrite);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (bwr != null) {
					bwr.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

Detail : Initialize a java.io.BufferedWriter object which takes a java.io.FileWriter object as argument which is linked to the original file which we need to write. write() method of java.io.BufferedWriter takes a string to be written as argument. At the end, do not forget to close the writer.

Method 2: Using java.io.FileWriter

	static void writeUsingFileWriter(String outFilePath, String stringToWrite) {
		FileWriter fwr = null;
		try {
			fwr = new FileWriter(outFilePath);
			fwr.write(stringToWrite);
	        } catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fwr != null) {
					fwr.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

Detail : Initialize a java.io.FileWriter object which is linked to the original file which we need to write. write() method of java.io.FileWriter takes a string to be written as argument. At the end, do not forget to close the writer.
Method 3: Using Apache Commons library

	static void usingApacheCommons(String outFilePath, String stringToWrite) {
		FileWriter fwr = null;
		try {
			fwr = new FileWriter(outFilePath);
			IOUtils.write(stringToWrite, fwr);
		} catch (FileNotFoundException fne) {
			fne.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fwr != null) {
					fwr.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

Detail : Initialize a java.io.FileWriter object with the target file as argument. write() method of IOUtils from Apache commons library takes an input string and writes it to a writer. At the end, do not forget to close the file writer. This method requires Apache commons library to be on the classpath. Get it here

Note : All the above methods write a fixed string or a string generated programmatically to a file but there may be a situation where the string to be written should be read from another file. Refer this post for details.

Let’s tweak in :

  1. java.io.FileWriter throws a java.io.FileNotFoundException since there is always a risk of file location being invalid (either the file is not present or the location denotes a directory).
  2. write() method throws a java.io.IOException since many kinds of errors may arise during this operation such as file is corrupt, there are no write permissions, no disk space etc.
  3. java.io.FileWriter has constructors which take a java.io.File object or a file name in String format as arguments.
  4. Closing a java.io.BufferedWriter closes the underlying java.io.Writer and there is no need to close it explicitly.
  5. If you are using jdk 7 and above for development and declare the writer object as try(BufferedWriter bwr = new BufferedWriter(new File(filePath))) and you don’t need to explicitly close the stream or reader. This is called try-with-resources construct.
  6. IOUtils has overloaded versions of write() method which take a java.lang.StringBuffer object and write to either a java.io.Writer or a java.io.OutputStream.

Mark Your Impression

Close Menu