Turn: Java read and write file various methods and performance comparison

Source: Internet
Author: User

Doing Java for so long, has been doing web-related projects, some basic classes have almost forgotten. Often want to pick up, but always for some reasons, can not be fulfilled.

In fact, there is no time, but sometimes tired of summing up, this hollow, determined to throw away all to pick up.

File reading and writing is a frequently encountered work in a project, sometimes because of maintenance, and sometimes new features development. Our task is always very heavy, the pace of work is fast, we can not stop to summarize.

There are several common ways to read and write files:

1, byte Read and write (Inputstream/outputstream)

2, character reading (Filereader/filewriter)

3, line read (Bufferedreader/bufferedwriter)

Code (take read as an example):

Copy Code
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 read class </b><br/>
* 1, read the contents of the file by byte <br/>
* 2, read the contents of the file by character <br/>
* 3, read the contents of the file by line <br/>
* @author Qin_xijuan
*
*/
public class Fileoperate {

private static final String File_path = "D:/work/the List of Beautiful Music.txt";

/**
* Read the contents of the file in 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 a superclass of all classes that represent byte input streams.
InputStream ins = null;
try{
FileInputStream: Gets the 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 the contents of the file in a character unit
* @param FilePath
*/
public static void Readfilebycharacter (String filePath) {
File File = new file (FilePath);
FileReader: A handy 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 contents in behavioral units
* @param FilePath
*/
public static void Readfilebyline (String filePath) {
File File = new file (FilePath);
BufferedReader: Reads text from the character input stream, buffering individual characters, enabling efficient reading of characters, arrays, and rows.
BufferedReader buf = null;
try{
FileReader: A handy 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);
}
}
Copy Code
-----------------------------------------------------------------Split Line----------------------------------------- ------------------------------------

After two peer's point, I made a few changes to the previously written file, and read and write a 1.2M text file to test the performance of each method. Judging from the results of multiple tests, the line reads and writes is Java.nio more efficient.

The following code has been modified:

Copy Code
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 read class </b><br/>
* 1, read the contents of the file by byte <br/>
* 2, read the contents of the file by character <br/>
* 3, read the contents of the file by line <br/>
*
* @author Qin_xijuan
*
*/
public class Fileoperate {

private static final String File_path = "D:/work/jipinwodi.txt";

/**
* Read and Write file contents in bytes
*
* @param filePath
*: File path to read
*/
public static void Readfilebybyte (Stri ng FilePath) {
File File = new file (filePath);
//InputStream: This abstract class is a superclass of all classes that represent byte input streams.
InputStream ins = null;
OutputStream outs = null;
try {
//FileInputStream: Gets the 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 contents in characters
*
* @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) { br> try {
Reader.close ();
Writer.close ();
} catch (IOException e) {
E.printstacktrace ();
}
}
}
}

/**
* Reads and writes the contents of the file in the behavior unit
*
* @param filePath
*/
public static void Readfilebyline (String filePath) {
File File = new file (FilePath);
//BufferedReader: reads text from the character input stream, buffering individual characters, enabling efficient reading of characters, arrays, and rows.
BufferedReader bufreader = null;
BufferedWriter bufwriter = null;
try {
//FileReader: A handy 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
//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 ();
}
}
}
}

/**
* Output one file to another file using Java.nio bytebuffer bytes
*
* @param filePath
*/
public static void Readfilebybyb Ebuffer (String filePath) {
FileInputStream in = null;
FileOutputStream out = null;
try {
//Gets the input and output stream of the source and destination files
in = new FileInputStream (FilePath),
out = new FileOutputStream ("D:/work/readfi LeByBybeBuffer.txt ");
//Get Input output channel
FileChannel fcin = In.getchannel ();
FileChannel fcout = Out.getchannel ();
Bytebuffer buffer = bytebuffer.allocate (1024); The
while (true) {
//Clear method resets the buffer so that it can accept the read-in Data
Buffer.clear ();
//reads 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 the newly 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);
}
}
Copy Code
In the main method, after calling each method, there are five sets of data, which tell me the time (in milliseconds) that I read and write the file 5 times.

For Java.nio please refer to: http://www.iteye.com/topic/834447

Turn: Java read and write file various methods and performance comparison

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.