Java file read and write (TXT type read and write and append content)

Source: Internet
Author: User

Learn something new and grow stronger every day, hehe.

One: Java reading and writing

Read the file:

FileInputStream
Create a FileInputStream by opening a connection to the actual file that passes through the path name in the file system

Name specifies. Creates a new FileDescriptor object to represent this file connection.
InputStreamReader
InputStreamReader is a bridge of byte flow to character streams: it reads bytes using the specified charset and decodes them into words

Character. It uses a character set that can be specified by name or explicitly given, or it may accept the platform default character set.
BufferedReader
Reads text from the character input stream, buffering individual characters to provide efficient reading of characters, arrays, and rows. Buffer can be specified

Size, or you can use the default size. In most cases, the default value is large enough.
StringBuffer
A thread-safe variable character sequence. A string buffer similar to strings, but cannot be modified. Although at any point in time

It contains a particular sequence of characters, but some method calls can change the length and content of the sequence.

public static void Main (string[] args) {

Read File contents
File A = new file ("C:/add2.txt");
if (a.exists ()) {
FileInputStream fi = new FileInputStream (a);
InputStreamReader ISR = new InputStreamReader (FI, "GBk");
BufferedReader Bfin = new BufferedReader (ISR);
String rline = "";
while ((Rline = Bfin.readline ())!=null) {
System.out.println (Rline);
}
}

}

Write file:

In Java write files, you typically use FileOutputStream and filewriter,filewriter to write only text files. FileOutputStream also often combine Bufferedoutputstream. Because the actual application of writing text files in the majority of the situation. So the following test produces three different ways to generate a file of the same number of rows and sizes in different ways.

Import Java.io.File;
Import Java.io.FileOutputStream;
Import java.io.*;

public class Filetest {
Public Filetest () {
}

public static void Main (string[] args) {
FileOutputStream out = null;
FileOutputStream outstr = null;
Bufferedoutputstream Buff=null;
FileWriter FW = NULL;
int count=1000;//number of write file lines
try {
out = new FileOutputStream (New File ("C:/add.txt"));
Long begin = System.currenttimemillis ();
for (int i = 0; i < count; i++) {
Out.write ("Test Java file operations \ r \ n". GetBytes ());
}
Out.close ();
Long end = System.currenttimemillis ();
System.out.println ("FileOutputStream Execution Time:" + (End-begin) + "Hao second");

outstr = new FileOutputStream (New File ("C:/add0.txt"));
Buff=new Bufferedoutputstream (OUTSTR);
Long begin0 = System.currenttimemillis ();
for (int i = 0; i < count; i++) {
Buff.write ("Test Java file operations \ r \ n". GetBytes ());
}
Buff.flush ();
Buff.close ();
Long end0 = System.currenttimemillis ();
System.out.println ("Bufferedoutputstream Execution Time:" + (End0-begin0) + "Hao second");


            fw = new FileWriter ("C:/add2.txt");
            Long begin3 = System.currenttimemillis ();
            for (int i = 0; i < count; i++) {
 &nb sp;              fw.write ("Test Java file operations \ r \ n");
           }
                         Fw.close ();
            Long end3 = System.currenttimemillis ();
            System.out.println ("FileWriter Execution Time:" + ( end3-begin3) + "Hao second");

catch (Exception e) {
E.printstacktrace ();
}
finally {
try {
Fw.close ();
Buff.close ();
Outstr.close ();
Out.close ();
catch (Exception e) {
E.printstacktrace ();
}
}
}


}

The following results have been executed several times, taking the data that is often present, because it is simply compared and does not make detailed statistics.

1. When the count=1000, that is, write the file 1000 lines, write the file size of 18.5KB:
FileOutputStream execution time consuming: 46 Hao seconds
Bufferedoutputstream execution time consuming: 31 Hao seconds
FileWriter execution time consuming: 15 Hao seconds


2. When the count=10000, that is, write the file 10000 lines, write the file size of 185KB:
FileOutputStream execution time consuming: 188 Hao seconds
Bufferedoutputstream execution time consuming: 32 Hao seconds
FileWriter execution time consuming: 16 Hao seconds

3. When the count=100000, that is, write the file 100000 lines, write the file size of 1856KB:
FileOutputStream execution time consuming: 1266 Hao seconds
Bufferedoutputstream execution time consuming: 125 Hao seconds
FileWriter execution time consuming: 93 Hao seconds

4. When the count=1000000, that is, write the file 1000000 lines, write the file size of 18555KB:
FileOutputStream execution time consuming: 12063 hao seconds
Bufferedoutputstream execution time consuming: 1484 Hao seconds
FileWriter execution time consuming: 969 Hao seconds


As can be seen from the above data, it is not good to write a file without buffering the stream bufferedoutputstream,fileoutputstream. When writing 1000000-line files, FileOutputStream is 11094 milliseconds (11 seconds) slower than FileWriter, and Bufferedoutputstream is 515 milliseconds slower than filewriter.
Do not underestimate the time of the few seconds. When the amount of data is very large, this performance gap will be very large. When the universal Data Migration Tool exports the database 20 million records to generate the SQL script file, the performance performance difference is more than 10 minutes.

Second: Java file append content

Package com.thread.test;

Import Java.io.FileWriter;
Import java.io.IOException;
Import Java.io.RandomAccessFile;

public class Appendtofile {

public static void Appendmethoda (String fileName,

String content) {
try {
Open a random Access file stream, read and write
Randomaccessfile randomfile = new Randomaccessfile (fileName, "RW");
File length, number of bytes
Long filelength = Randomfile.length ();
Moves the write file pointer to the end of the file.
Randomfile.seek (filelength);
Randomfile.writebytes (content);
Randomfile.close ();
catch (IOException e) {
E.printstacktrace ();
}
}

public static void Appendmethodb (string fileName, string content) {
try {
Opens a write file, and the second argument in the constructor, true, indicates that the file is written in an append form
FileWriter writer = new FileWriter (FileName, true);
Writer.write (content);
Writer.close ();
catch (IOException e) {
E.printstacktrace ();
}
}
public static void Main (string[] args) {
String fileName = "D:/t2.txt";
String content = "New append!";
Append files by Method a
Appendtofile.appendmethoda (fileName, content);
Appendtofile.appendmethoda (FileName, "append end.") n ");
Show file contents
Readfromfile.readfilebylines (FileName);
Append files by Method b
Appendtofile.appendmethodb (fileName, content);
Appendtofile.appendmethodb (FileName, "append end.") n ");
Show file contents
Readfromfile.readfilebylines (FileName);
}
}

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.