English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java file read and write IO/Detailed code and summary of NIO and performance comparison

Having been engaged in Java for so long, I have been working on WEB-related projects, and some basic classes are almost forgotten. I often want to pick them up, but for some reasons, I can't as I wish.

In fact, it's not that we don't have time, but sometimes we are too tired to summarize. Now that I have some time, I have decided to pick up everything that has been lost.

File read/write is a common task in projects, sometimes for maintenance, sometimes for new feature development. Our tasks are always heavy, and the pace of work is fast, so fast that we cannot stop to summarize.

There are several commonly used methods for file read/write

1, byte read/write (InputStream/, OutputStream

2, character reading (FileReader/, FileWriter)

3, line reading (BufferedReader/BufferedWriter)

Code (take reading as an example):

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
/** 
 * <b>File Reading Class</b><br /> 
 * 1、Read file content by byte<br /> 
 * 2、Read file content by character<br /> 
 * 3、Read file content by line<br /> 
 * @author qin_xijuan 
 * 
 */
public class FileOperate {
	private static final String FILE_PATH = "d:/work/"the List of Beautiful Music.txt";
	/** 
   * Read file content byte by byte 
   * @param filePath: The file path to be read 
   */
	public static void readFileBybyte(String filePath) {
		File file = new File(filePath);
		// InputStream: This abstract class is the superclass of all classes representing byte input streams. 
		InputStream ins = null ;
		try{
			// FileInputStream: Obtain input bytes from a file in the file system. 
			ins = new FileInputStream(file);
			int temp ;
			// read(): Reads the next byte of data from the input stream. 
			while((temp = ins.read())!=-1){
				System.out.write(temp);
			}
		}
		catch(Exception e){
			e.getStackTrace();
		}
		finally{
			if (ins != null){
				try{
					ins.close();
				}
				catch(IOException e){
					e.getStackTrace();
				}
			}
		}
	}
	/** 
   * Read file content character by character 
   * @param filePath 
   */
	public static void readFileByCharacter(String filePath){
		File file = new File(filePath);
		// FileReader: a convenient class for reading character files. 
		FileReader reader = null;
		try{
			reader = new FileReader(file);
			int temp ;
			while((temp = reader.read()) != -1){
				if (((char) temp) != '\r') {
					System.out.print((char) temp);
				}
			}
		}
		catch(IOException e){
			e.getStackTrace();
		}
		finally{
			if (reader != null){
				try {
					reader.close();
				}
				catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	/** 
   * Read file content line by line 
   * @param filePath 
   */
	public static void readFileByLine(String filePath){
		File file = new File(filePath);
		// BufferedReader: Reads text from character input streams, buffering each character to efficiently read characters, arrays, and lines. 
		BufferedReader buf = null;
		try{
			// FileReader: a convenient class for reading character files. 
			buf = new BufferedReader(new FileReader(file));
			// buf = new BufferedReader(new InputStreamReader(new FileInputStream(file))); 
			String temp = null ;
			while ((temp = buf.readLine()) != null ){
				System.out.println(temp);
			}
		}
		catch(Exception e){
			e.getStackTrace();
		}
		finally{
			if(buf != null){
				try{
					buf.close();
				}
				catch (IOException e) {
					e.getStackTrace();
				}
			}
		}
	}
	public static void main(String args[]) {
		readFileBybyte(FILE_PATH);
		readFileByCharacter(FILE_PATH);
		readFileByLine(FILE_PATH);
	}
}

//-----------------------------------------------------------------Separator-----------------------------------------------------------------------------

After being pointed out by two colleagues, I made some modifications to the file I wrote before and tested it by reading and writing a1.2To test the performance of each method, I used a text file M and the results from multiple tests show that line reading is more efficient in Java.nio.

The code after modification is as follows:

package com.waddell.basic;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/** 
 * <b>File Reading Class</b><br /> 
 * 1、Read file content by byte<br /> 
 * 2、Read file content by character<br /> 
 * 3、Read file content by line<br /> 
 * 
 * @author qin_xijuan 
 * 
 */
public class FileOperate {
	private static final String FILE_PATH = "d:/work/jipinwodi.txt";
	/** 
   * Read and write file content by bytes 
   * 
   * @param filePath 
   *      :The file path to be read 
   */
	public static void readFileBybyte(String filePath) {
		File file = new File(filePath);
		// InputStream: This abstract class is the superclass of all classes representing byte input streams. 
		InputStream ins = null;
		OutputStream outs = null;
		try {
			// FileInputStream: Obtain input bytes from a file in the file system. 
			ins = new FileInputStream(file);
			outs = new FileOutputStream("d:/work/readFileByByte.txt");
			int temp;
			// read(): Reads the next byte of data from the input stream. 
			while ((temp = ins.read()) != -1) {
				outs.write(temp);
			}
		}
		catch (Exception e) {
			e.getStackTrace();
		}
		finally {
			if (ins != null && outs != null) {
				try {
					outs.close();
					ins.close();
				}
				catch (IOException e) {
					e.getStackTrace();
				}
			}
		}
	}
	/** 
   * Read and write file content by character units 
   * 
   * @param filePath 
   */
	public static void readFileByCharacter(String filePath) {
		File file = new File(filePath);
		// FileReader: a convenient class for reading character files. 
		FileReader reader = null;
		FileWriter writer = null;
		try {
			reader = new FileReader(file);
			writer = new FileWriter("d:/work/readFileByCharacter.txt");
			int temp;
			while ((temp = reader.read()) != -1) {
				writer.write((char)temp);
			}
		}
		catch (IOException e) {
			e.getStackTrace();
		}
		finally {
			if (reader != null && writer != null) {
				try {
					reader.close();
					writer.close();
				}
				catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	/** 
   * Read and write file content by line units 
   * 
   * @param filePath 
   */
	public static void readFileByLine(String filePath) {
		File file = new File(filePath);
		// BufferedReader: Reads text from character input streams, buffering each character to efficiently read characters, arrays, and lines. 
		BufferedReader bufReader = null;
		BufferedWriter bufWriter = null;
		try {
			// FileReader: a convenient class for reading character files. 
			bufReader = new BufferedReader(new FileReader(file));
			bufWriter = new BufferedWriter(new FileWriter("d:/work/readFileByLine.txt"));
			// buf = new BufferedReader(new InputStreamReader(new 
			// new FileInputStream(file))); 
			String temp = null;
			while ((temp = bufReader.readLine()) != null) {
				bufWriter.write(temp+"\n");
			}
		}
		catch (Exception e) {
			e.getStackTrace();
		}
		finally {
			if (bufReader != null && bufWriter != null) {
				try {
					bufReader.close();
					bufWriter.close();
				}
				catch (IOException e) {
					e.getStackTrace();
				}
			}
		}
	}
	/** 
   * Use Java.nio ByteBuffer to output a file to another file 
   * 
   * @param filePath 
   */
	public static void readFileByBybeBuffer(String filePath) {
		FileInputStream in = null;
		FileOutputStream out = null;
		try {
			// Get input and output streams of the source and target files  
			in = new FileInputStream(filePath);
			out = new FileOutputStream("d:/work/readFileByBybeBuffer.txt");
			// Get input and output channels 
			FileChannel fcIn = in.getChannel();
			FileChannel fcOut = out.getChannel();
			ByteBuffer buffer = ByteBuffer.allocate(1024);
			while (true) {
				// The clear method resets the buffer so that it can accept read-in data 
				buffer.clear();
				// Read data from the input channel to the buffer 
				int r = fcIn.read(buffer);
				if (r == -1) {
					break;
				}
				// The flip method allows the buffer to write new read-in data to another channel  
				buffer.flip();
				fcOut.write(buffer);
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			if (in != null && out != null) {
				try {
					in.close();
					out.close();
				}
				catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	public static long getTime(){
		return System.currentTimeMillis();
	}
	public static void main(String args[]) {
		long time1 = getTime() ;
		// readFileByByte(FILE_PATH);// 8734,8281,8000,7781,8047 
		// readFileByCharacter(FILE_PATH);// 734, 437, 437, 438, 422 
		// readFileByLine(FILE_PATH);// 110, 94, 94, 110, 93 
		readFileByBybeBuffer(FILE_PATH);
		// 125, 78, 62, 78, 62 
		long time2 = getTime() ;
		System.out.println(time2-time1);
	}
}

In the main method, after calling each method, there are five groups of data, which are my5This is the time (in milliseconds) for this read and write file test.

For more information about Java.nio, please refer to: https://www.oldtoolbag.com/article/131338.htm

Personal Test:

public static void main(String args[]) {
	long time1 = getTime() ;
	//     readFileByByte(FILE_PATH);   //2338,2286 
	//     readFileByCharacter(FILE_PATH);//160,162,158 
	//     readFileByLine(FILE_PATH);   //46,51,57 
	//    readFileByBybeBuffer(FILE_PATH);//19,18,17 
	//    readFileByBybeBuffer(FILE_PATH);//2048: 11,13 
	//    readFileByBybeBuffer(FILE_PATH);//1024*100 100k,711k: 6,6 
	//    readFileByBybeBuffer(FILE_PATH);//1024*100 100k,1422k: 7 
	//    readFileByBybeBuffer(FILE_PATH);//1024*100 100k,9951k: 49,48 
	//    readFileByBybeBuffer(FILE_PATH);//1024*1000 1M,711k: 7,7 
	//    readFileByBybeBuffer(FILE_PATH);//1024*1000 1M,1422k: 7,8 
	//    readFileByBybeBuffer(FILE_PATH);//1024*1000 1M,9951k: 48,49 
	//    readFileByBybeBuffer(FILE_PATH);//1024*10000 10M,711k: 21,13,17 
	//    readFileByBybeBuffer(FILE_PATH);//1024*10000 10M,1422k: 16,17,14,15 
	//    readFileByBybeBuffer(FILE_PATH);//1024*10000 10M,9951k:64,60 
	long time2 = getTime() ;
	System.out.println(time2-time1);
}

Summary

That is all about Java file read and write IO in this article/All the detailed code and summary of NIO and performance comparison are provided, hoping it will be helpful to everyone. Those who are interested can continue to read other related topics on this site, and welcome to leave a message if there are any deficiencies. Thank you for your support to this site!

Statement: The content of this article is from the Internet, the copyright belongs to the original author, the content is contributed and uploaded by Internet users spontaneously, this website does not own the copyright, has not been manually edited, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please send an email to codebox.com (replace # with @ when sending an email) to report violations, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.

You May Also Like