Category Archives: file

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

 

Advertisements

Java :Different ways of Reading a text file


There are multiple ways of reading a text file in Java as below:

  1. BufferedReader
  2. FileReader
  3. Scanner
  4. Stream/Files (java 8): Read all file lines
  5. Paths (Java 8) : Read text file as String

Every way have something different as BufferedReader provides buffering of data for fast reading and Scanner provides parsing ability while we can use both BufferedReader and Scanner to read a text file line by line in Java.

Java 8 introduced Stream class java.util.stream which provides a lazy and more efficient way to read a file.

File Reading By BufferedReader

This method reads text from a character-input stream. It does buffering for efficient reading of characters, arrays, and lines.The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example,


BufferedReader in = new BufferedReader(Reader in, int size);
try {
    File file = new File(FILE);
    BufferedReader br = new BufferedReader(new FileReader(file));
    String st;
    while ((st = br.readLine()) != null)
	System.out.println(st);
} catch (IOException ex) {
	ex.printStackTrace();
}

Note : In below code examples not follow usual practices of writing good code like flushing/closing streams, Exception-Handling etc, to reduce number of lines code for better understanding.

File Reading By FileReader

FileReader is convenient class for reading character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate.


Constructors defined in this class are:
FileReader(File file) : Creates a new FileReader, given the File to read from.

FileReader(FileDescriptor fd): Creates a new FileReader, given the FileDescriptor to read from.

FileReader(String fileName): Creates a new FileReader, given the name of the file to read from.
try {
     FileReader fr = new FileReader(FILE);

     int i;
     while ((i = fr.read()) != -1)
	System.out.print((char) i);
} catch (IOException ex) {
	ex.printStackTrace();
}

File Reading By Scanner

A scanner can parse primitive types and strings using regular expressions and breaks its input into tokens using a delimiter pattern, which by default matches white space. The resulting tokens may then be converted into values of different types using the various next methods.

try {
	File file = new File(FILE);
	Scanner sc = new Scanner(file);

	while (sc.hasNextLine())
	System.out.println(sc.nextLine());
	} catch (Exception ex) {
	ex.printStackTrace();
	}

Read file by scanner without loop

File file = new File(FILE);
try {
	Scanner sc = new Scanner(file);
	// Use delimiter \Z for next line
	sc.useDelimiter("\Z");

	System.out.println(sc.next());
} catch (Exception ex) {
	ex.printStackTrace();
}

File Reading By Stream (Java8)

Files.readAllLines() method read all lines from a file and ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown.
Bytes from the file are decoded into characters using the specified charset.


public static List readAllLines(Path path,Charset cs)throws IOException

This method recognizes the following as line terminators:
CARRIAGE RETURN followed by LINE FEED (u000D followed by u000A)
u000A, LINE FEED
u000D, CARRIAGE RETURN
List<String> lines = Collections.emptyList();
		try {
			lines = Files.readAllLines(Paths.get(FILE), StandardCharsets.UTF_8);
			Iterator<String> itr = lines.iterator();
			while (itr.hasNext())
				System.out.println(itr.next());
		} catch (IOException e) {
			e.printStackTrace();
		}

File Reading By Paths (Java8)

try {
			String data = new String(Files.readAllBytes(Paths.get(FILE)));
			System.out.println(data);
		} catch (Exception ex) {
			ex.printStackTrace();
		}

Complete Example

In below example  covered all the above cases.

Test Data


Index     Name      Age       Gender         Employment     Address   
1         Saurabh   36        M              Private        Sector-120 Noida 
2         Gaurav    34        M              Business       Sector-14 Gurgaon 
3         Bharti    30        M              Government     Sector-120 Noida 
package com.file;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

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

	public static void main(String[] args) {
		FileReadingWay s = new FileReadingWay();
		System.out.println("===============Read File By Buffered Reader================");
		s.readFileByBufferedReader();
		System.out.println("===============Read File By File Reader================");
		s.readFileByFileReader();
		System.out.println("===============Read File By Scanner================");
		s.readFileByScanner();
		System.out.println("===============Read File By Scanner without Loop================");
		s.readFileByScannerWithOutLoop();
		System.out.println("===============Read All Files================");
		s.readFileByReadAllFiles();
		System.out.println("===============Read Text File and String================");
		s.readTextFileAsString();
	}

	private void readFileByBufferedReader() {
		try {
			File file = new File(FILE);

			BufferedReader br = new BufferedReader(new FileReader(file));

			String st;
			while ((st = br.readLine()) != null)
				System.out.println(st);
		} catch (IOException ex) {
			ex.printStackTrace();
		}

	}

	private void readFileByFileReader() {
		System.out.println();
		try {
			FileReader fr = new FileReader(FILE);

			int i;
			while ((i = fr.read()) != -1)
				System.out.print((char) i);
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		System.out.println();
	}

	private void readFileByScanner() {

		try {
			File file = new File(FILE);
			Scanner sc = new Scanner(file);

			while (sc.hasNextLine())
				System.out.println(sc.nextLine());
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	private void readFileByScannerWithOutLoop() {
		File file = new File(FILE);
		try {
			Scanner sc = new Scanner(file);
			// Use delimiter \Z for next line
			sc.useDelimiter("\Z");

			System.out.println(sc.next());
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	private void readFileByReadAllFiles() {
		List<String> lines = Collections.emptyList();
		try {
			lines = Files.readAllLines(Paths.get(FILE), StandardCharsets.UTF_8);
			Iterator<String> itr = lines.iterator();
			while (itr.hasNext())
				System.out.println(itr.next());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void readTextFileAsString() {
		try {
			String data = new String(Files.readAllBytes(Paths.get(FILE)));
			System.out.println(data);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}

Output


===============Read File By Buffered Reader================
Index     Name      Age       Gender         Employment     Address   
1         Saurabh   36        M              Private        Sector-120 Noida 
2         Gaurav    34        M              Business       Sector-14 Gurgaon 
3         Bharti    30        M              Government     Sector-120 Noida 
===============Read File By File Reader================

Index     Name      Age       Gender         Employment     Address   
1         Saurabh   36        M              Private        Sector-120 Noida 
2         Gaurav    34        M              Business       Sector-14 Gurgaon 
3         Bharti    30        M              Government     Sector-120 Noida 
===============Read File By Scanner================
Index     Name      Age       Gender         Employment     Address   
1         Saurabh   36        M              Private        Sector-120 Noida 
2         Gaurav    34        M              Business       Sector-14 Gurgaon 
3         Bharti    30        M              Government     Sector-120 Noida 
===============Read File By Scanner without Loop================
Index     Name      Age       Gender         Employment     Address   
1         Saurabh   36        M              Private        Sector-120 Noida 
2         Gaurav    34        M              Business       Sector-14 Gurgaon 
3         Bharti    30        M              Government     Sector-120 Noida 
===============Read All Files================
Index     Name      Age       Gender         Employment     Address   
1         Saurabh   36        M              Private        Sector-120 Noida 
2         Gaurav    34        M              Business       Sector-14 Gurgaon 
3         Bharti    30        M              Government     Sector-120 Noida 
===============Read Text File and String================
Index     Name      Age       Gender         Employment     Address   
1         Saurabh   36        M              Private        Sector-120 Noida 
2         Gaurav    34        M              Business       Sector-14 Gurgaon 
3         Bharti    30        M              Government     Sector-120 Noida 

References