Write to a file in Java

There are several ways to write to a Java text file. Java supports different types of api to write file content. For example, write character by character, write line by line or write byte by by byte.



Write to text file in Java

In this post, we explained five types of writing text file in Java.

  • Writing to a text file using FileWriter
  • Writing to a text file using FileWriter line by line
  • Writing to a text file using FileOutputStream
  • Writing to a text file using PrintWriter
  • Writing to a text file using NIO Files

Sample file

The file used to store sample content in the programs is data/test.txt.



Write to a text file using FileWriter

The FileWriter class is used to write in a text file using java. BufferWriter is used to cache data and write smoothly in a file. In the FileWriter class, write () api writes content into a text file. It is important to close the BufferWriter and FileWriter connections. If the file is not available at the specified location, no write permission or problem with accessing this file, an exception will be thrown.

package com.yawintutor;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

public class JavaFileWriter {

	public static void main(String[] args) throws Exception {
		String content = "This is a example for writing content into a text file using java";
		writeFile("data/test.txt", content);
		System.out.println("YAWIN:INFO:FILE CREATED SUCCESSFULLY IN data/test.txt");
	}

	public static void writeFile(String fileName, String content) throws Exception {
		FileWriter fw = null;
		BufferedWriter bw = null;
		try {
			fw = new FileWriter(new File(fileName));
			bw = new BufferedWriter(fw);
			bw.write(content);
		} catch (Exception e) {
			System.out.println("YAWIN:ERROR:" + e.getMessage());
			throw e;
		} finally {
			try {
				bw.close();
			} catch (Exception e) {
			}
			try {
				fw.close();
			} catch (Exception e) {
			}
		}

	}

}

Output

YAWIN:INFO:FILE CREATED SUCCESSFULLY IN data/test.txt


Writing to a text file using FileWriter line by line

In this example, the FileWriter class is used to write a text file. The data is written line by line here. The array list is iterated and read one by one and writes to the text file. If we want to write a large content in a single file, read line by line and write in a file instead of creating a single string. BufferWriter will maintain the data to be sent quickly and ensure that no hardware failure occurs while writing on a permanent storage device, such as a hard disk.

package com.yawintutor;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;

public class JavaFileWriterList {

	public static void main(String[] args) throws Exception {
		ArrayList<String> list = new ArrayList<String>();
		list.add("This is a example for writing content into a text file using java");
		list.add("This is second line");
		list.add("This is third line");
		writeFile("data/test.txt", list);
		System.out.println("YAWIN:INFO:FILE CREATED SUCCESSFULLY IN data/test.txt");
	}

	public static void writeFile(String fileName, List<String> list) throws Exception {
		FileWriter fw = null;
		BufferedWriter bw = null;
		try {
			fw = new FileWriter(new File(fileName));
			bw = new BufferedWriter(fw);
			for (int i = 0; list != null && i < list.size(); i++) {
				bw.write(list.get(i));
				bw.write("\n");
			}
		} catch (Exception e) {
			System.out.println("YAWIN:ERROR:" + e.getMessage());
			throw e;
		} finally {
			try {
				bw.close();
			} catch (Exception e) {
			}
			try {
				fw.close();
			} catch (Exception e) {
			}
		}

	}

}

Output

YAWIN:INFO:FILE CREATED SUCCESSFULLY IN data/test.txt


Writing to a text file using FileOutputStream

FileOutputStream is another way to write a file in Java. It reads file content as a data stream and writes in the file. FileOutputStream is mostly used to write non-text files like image, video files, where the content is not readable. These files are viewed using specialized applications.

package com.yawintutor;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

public class JavaFileStream {

	public static void main(String[] args) throws Exception {
		String content = "This is a example for writing content into a text file using java";
		writeFile("data/test.txt", content);
		System.out.println("YAWIN:INFO:FILE CREATED SUCCESSFULLY IN data/test.txt");
	}

	public static void writeFile(String fileName, String content) throws Exception {
		FileOutputStream fos = null;
		BufferedOutputStream bos = null;
		try {
			fos = new FileOutputStream(new File(fileName));
			bos = new BufferedOutputStream(fos);
			bos.write(content.getBytes());
		} catch (Exception e) {
			System.out.println("YAWIN:ERROR:" + e.getMessage());
			throw e;
		} finally {
			try {
				bos.close();
			} catch (Exception e) {
			}
			try {
				fos.close();
			} catch (Exception e) {
			}
		}

	}

}

Output

YAWIN:INFO:FILE CREATED SUCCESSFULLY IN data/test.txt


Writing to a text file using PrintWriter

The other way to write a file is by using the PrintWriter class. The PrintWriter class is used to write data on any printing device. If a file is configured instead of a printing device, the data is stored in a permanent storage device.

package com.yawintutor;

import java.io.BufferedWriter;
import java.io.File;
import java.io.PrintWriter;

public class JavaPrintWriter {

	public static void main(String[] args) throws Exception {
		String content = "This is a example for writing content into a text file using java";
		writeFile("data/test.txt", content);
		System.out.println("YAWIN:INFO:FILE CREATED SUCCESSFULLY IN data/test.txt");
	}

	public static void writeFile(String fileName, String content) throws Exception {
		PrintWriter pw = null;
		BufferedWriter bw = null;
		try {
			pw = new PrintWriter(new File(fileName));
			bw = new BufferedWriter(pw);
			bw.write(content);
		} catch (Exception e) {
			System.out.println("YAWIN:ERROR:" + e.getMessage());
			throw e;
		} finally {
			try {
				bw.close();
			} catch (Exception e) {
			}
			try {
				pw.close();
			} catch (Exception e) {
			}
		}
	}
}

Output

YAWIN:INFO:FILE CREATED SUCCESSFULLY IN data/test.txt


Writing to a text file using NIO Files

The NIO package FileWriter class is used to write data over the network. When data is sent over the network, issues like network connectivity stop sending data. FileWriter handles all kinds of network problems and ensures a smooth way to write data to a file via the network.

package com.yawintutor;

import java.nio.file.Files;
import java.nio.file.Paths;

public class JavaFileWriterNIO {

	public static void main(String[] args) throws Exception {
		String content = "This is a example for writing content into a text file using java";
		writeFile("data/test.txt", content);
		System.out.println("YAWIN:INFO:FILE CREATED SUCCESSFULLY IN data/test.txt");
	}

	public static void writeFile(String fileName, String content) throws Exception {
		try {
			Files.write(Paths.get(fileName), content.getBytes());
		} catch (Exception e) {
			System.out.println("YAWIN:ERROR:" + e.getMessage());
			throw e;
		}
	}

}

Output

YAWIN:INFO:FILE CREATED SUCCESSFULLY IN data/test.txt



Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *