Java: Different Ways to writing in text File


In java there are several ways to write in to a file as below:

  1. BufferedWriter
  2. FileWriter
  3. FileOutputStream
  4. Files & Path (Java 7)
  5. FileChannel
  6. RandomAccessFile to write in specific position
  7. FileLock
  8. Temporary File

File writing by BufferedWriter

BufferedWriter is almost similar to FileWriter but it uses internal buffer to write data into File.

It gives better performance when write operations are more because when more write operations then less IO operations.

String str = "Facing";
BufferedWriter writer = new BufferedWriter(new FileWriter(FILE));
writer.write(str);

writer.close();

when need to append more lines in file use File writer parameter with true to append more lines.

BufferedWriter writer = new BufferedWriter(new FileWriter(FILE, true));
writer.append(' ');
writer.append('Issues');
writer.append(' ');
writer.append('On');
writer.append(' ');
writer.append('IT');

writer.close();

File writing by FileWriter

FileWriter is the simplest way to write a file in java. FileWriter writes directly into Files and should be used only when number of writes are less. It also provides overloaded write method to write int, byte array and String to the File.

File file = new File(FILE);
FileWriter fr = null;
try {
   fr = new FileWriter(file);
   fr.write("Facing Issues On IT");
} catch (IOException e) {
   e.printStackTrace();
} finally {
try {
   fr.close();
} catch (IOException e) {
   e.printStackTrace();
}
}

File Writing by FileOutputStream

FileWriter and BufferedWriter are meant to write text to the file but when you need raw stream data to be written into file, you should use FileOutputStream to write file in java.

OutputStream os = null;
String data="FacingIssuesOnIt";
try {
	os = new FileOutputStream(new File(FILE));
	os.write(data.getBytes(), 0, data.length());
} catch (IOException e) {
	e.printStackTrace();
} finally {
try {
	os.close();
} catch (IOException e) {
	e.printStackTrace();
}
}

File Writing by Files

Java 7 introduced Files utility class and we can write a file using it’s write function, internally it’s using OutputStream to write byte array into file.

String data="FacingIssuesOnIt";
try {
	Files.write(Paths.get(FILE), data.getBytes());
} catch (IOException e) {
	e.printStackTrace();
}

File Writing by Channel

RandomAccessFile stream = new RandomAccessFile(FILE, "rw");
FileChannel channel = stream.getChannel();
String value = "FacingIssuesOnIT";
byte[] strBytes = value.getBytes();
ByteBuffer buffer = ByteBuffer.allocate(strBytes.length);
buffer.put(strBytes);
buffer.flip();
channel.write(buffer);
stream.close();
channel.close();

File Writing on specific position

public void writeFileOnParticularPosition() throws IOException {
int data = 2018;
int position = 5;
RandomAccessFile writer = new RandomAccessFile(FILE, "rw");
writer.seek(position);
writer.writeInt(dataPos1);
writer.close();
}

File Writing to when Locked

RandomAccessFile stream = new RandomAccessFile(FILE, "rw");
FileChannel channel = stream.getChannel();

FileLock lock = null;
try {
lock = channel.tryLock();
} catch (final OverlappingFileLockException e) {
stream.close();
channel.close();
}
stream.writeChars("FacingIssuesOnIT");
lock.release();

stream.close();
channel.close();

File Writing to Temporary File

String toWrite = "FacingIssuesOnIT";
File tmpFile = File.createTempFile("test", ".tmp");
FileWriter writer = new FileWriter(tmpFile);
writer.write(toWrite);
writer.close();

Complete Example

In this example covered all the ways (BufferedWriter, FileWriter, FileOutputStream and Files) of file writing.

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class FileWritingWay {
	private static final String FILE = "C:\Users\saurabh.gupta1\Desktop\Test Data.java";

	/**
	 * Here in this class you will see different ways to write in file by java
	 *
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) {
		try {
			System.out.println("===========Java Write File using FIleWriter============");
			writeFileUsingFileWriter();
			System.out.println("===========Java Write File using BufferedWriter============");
			writeFileUsingBufferedWriter();
			System.out.println("===========Java Write File using FileOutputStream============");
			writeUsingOutputStream();
			System.out.println("===========Java 7 Write File using Files and Paths============");
			writeUsingFiles();
			System.out.println("===========Java 7 Write File using Files and Paths============");
			WriteToFileWhenLocked();
			System.out.println("===========Write on temporary File============");
			writeToTemporaryFile();
			System.out.println("===========Write File using FileChannel============");
			writeFileByFileChannel();
			System.out
					.println("===========Write File using RandomAccessFile to write in specific position============");
			writeFileOnParticularPosition();
			System.out.println("===========Write File using DataOutputStream============");
			writeFileusingDataoutputStream();
		} catch (IOException ex) {
			ex.printStackTrace();
		}

	}

	/**
	 * Use file writer when number of write operations are less
	 *
	 * @param data
	 */
	private static void writeFileUsingFileWriter() {
		File file = new File(FILE);
		FileWriter fr = null;
		try {
			fr = new FileWriter(file);
			fr.write("facingIssuesOnIT");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fr.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * Use BufferedWriter when number of write operations are more It uses
	 * internal buffer to reduce real IO operations and saves time
	 *
	 * @param data
	 * @param noOfLines
	 */
	private static void writeFileUsingBufferedWriter() {
		try {
			String str = "Facing";
			BufferedWriter writer = new BufferedWriter(new FileWriter(FILE));
			writer.write(str);

			writer.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}

		// when need to append more lines in file use FileWrite with true as
		// below
		try {
			String str = "Facing";
			BufferedWriter writer = new BufferedWriter(new FileWriter(FILE, true));
			writer.append(' ');
			writer.append("Issues");
			writer.append(' ');
			writer.append("On");
			writer.append(' ');
			writer.append("IT");

			writer.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * Use Streams when you are dealing with raw data
	 *
	 * @param data
	 */
	private static void writeUsingOutputStream() {
		OutputStream os = null;
		String data = "FacingissuesonIT";
		try {
			os = new FileOutputStream(new File(FILE));
			os.write(data.getBytes(), 0, data.length());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * Use Files class from Java 1.7 to write files, internally uses
	 * OutputStream
	 *
	 * @param data
	 */
	private static void writeUsingFiles() {
		String data = "facingIssuesOnIT";
		try {
			Files.write(Paths.get(FILE), data.getBytes());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void writeUsingPrintWiter() throws IOException {
		FileWriter fileWriter = new FileWriter(FILE);
		PrintWriter printWriter = new PrintWriter(fileWriter);
		printWriter.print("FacingIssuesOnIT");
		printWriter.printf("Product name is %s and its price is %d $", "iPhone", 1000);
		printWriter.close();
	}

	public static void writeFileusingDataoutputStream() throws IOException {
		String value = "facingIssuesOnIT";
		FileOutputStream fos = new FileOutputStream(FILE);
		DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos));
		outStream.writeUTF(value);
		outStream.close();

	}

	public static void writeFileOnParticularPosition() throws IOException {
		int data = 2018;
		int position = 5;
		RandomAccessFile writer = new RandomAccessFile(FILE, "rw");
		writer.seek(position);
		writer.writeInt(data);
		writer.close();
	}

	public static void writeFileByFileChannel() throws IOException {
		RandomAccessFile stream = new RandomAccessFile(FILE, "rw");
		FileChannel channel = stream.getChannel();
		String value = "FacingIssuesOnIT";
		byte[] strBytes = value.getBytes();
		ByteBuffer buffer = ByteBuffer.allocate(strBytes.length);
		buffer.put(strBytes);
		buffer.flip();
		channel.write(buffer);
		stream.close();
		channel.close();

	}

	public static void writeToTemporaryFile() throws IOException {
		String toWrite = "FacingIssuesOnIT";
		File tmpFile = File.createTempFile("test", ".tmp");
		FileWriter writer = new FileWriter(tmpFile);
		writer.write(toWrite);
		writer.close();
	}

	public static void WriteToFileWhenLocked() throws IOException {
		RandomAccessFile stream = new RandomAccessFile(FILE, "rw");
		FileChannel channel = stream.getChannel();

		FileLock lock = null;
		try {
			lock = channel.tryLock();
		} catch (final OverlappingFileLockException e) {
			stream.close();
			channel.close();
		}
		stream.writeChars("FacingIssuesOnIT");
		lock.release();

		stream.close();
		channel.close();
	}
}

References

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s