Java file reading methods

Source: Internet
Author: User

I,

Summary 1

1. Read File Content by byte

2. Read File Content by character
3. Read File Content by row

4. Randomly Read File Content

Public class readfromfile {/*** reads files in bytes. It is often used to read binary files, files, sounds, images, and other files. */Public static void readfilebybytes (string filename) {file = new file (filename); inputstream in = NULL; try {system. out. println ("Read File Content in bytes, one byte at a time:"); // read one byte at a time in = new fileinputstream (File); int tempbyte; while (tempbyte = in. read ())! =-1) {system. out. write (tempbyte);} In. close ();} catch (ioexception e) {e. printstacktrace (); return;} Try {system. out. println ("Read File Content in bytes, read multiple bytes at a time:"); // read multiple bytes at a time byte [] tempbytes = new byte [100]; int byteread = 0; In = new fileinputstream (filename); readfromfile. showavailablebytes (in); // read multiple bytes into the byte array. byteread is the number of bytes read at a time. While (byteread = in. read (tempbytes ))! =-1) {system. Out. Write (tempbytes, 0, byteread) ;}} catch (exception E1) {e1.printstacktrace () ;}finally {If (in! = NULL) {try {In. close ();} catch (ioexception E1) {}}}/*** reads a file in characters and is often used to read text, numeric files */public static void readfilebychars (string filename) {file = new file (filename); reader = NULL; try {system. out. println ("Read File Content in characters, one byte at a time:"); // read one character at a time reader = new inputstreamreader (New fileinputstream (File); int tempchar; while (tempchar = reader. read ())! =-1) {// for Windows, \ r \ n indicates a line break when the two characters are together. // If the two characters are displayed separately, the rows are changed twice. // Therefore, block \ r or \ n. Otherwise, there will be a lot more blank lines. If (char) tempchar )! = '\ R') {system. out. print (char) tempchar) ;}} reader. close ();} catch (exception e) {e. printstacktrace ();} Try {system. out. println ("Read File Content in characters, read multiple bytes at a time:"); // read multiple characters at a time char [] tempchars = new char [30]; int charread = 0; reader = new inputstreamreader (New fileinputstream (filename); // read multiple characters into the character array, charread is the number of characters read at a time. While (charread = reader. read (tempchars ))! =-1) {// also blocked \ r does not show if (charread = tempchars. Length) & (tempchars [tempchars. Length-1]! = '\ R') {system. out. print (tempchars);} else {for (INT I = 0; I <charread; I ++) {If (tempchars [I] = '\ R ') {continue;} else {system. out. print (tempchars [I]) ;}}} catch (exception E1) {e1.printstacktrace () ;}finally {If (reader! = NULL) {try {reader. close ();} catch (ioexception E1) {}}}/*** reads the file in the unit of action, used to read row-oriented formatted files */public static void readfilebylines (string filename) {file = new file (filename); bufferedreader reader = NULL; try {system. out. println ("reads the content of a file in the unit of action, and reads the entire row at a time:"); reader = new bufferedreader (New filereader (File); string tempstring = NULL; int line = 1; // read a row at a time until null is the end of the file while (tempstring = Reader. Readline ())! = NULL) {// display the row number system. out. println ("line" + LINE + ":" + tempstring); line ++;} reader. close ();} catch (ioexception e) {e. printstacktrace ();} finally {If (reader! = NULL) {try {reader. close ();} catch (ioexception E1) {}}}/*** Randomly Read File Content */public static void readfilebyrandomaccess (string filename) {randomaccessfile randomfile = NULL; try {system. out. println ("randomly read a file:"); // open a random access file stream, in read-only mode randomfile = new randomaccessfile (filename, "R "); // file length, number of bytes long filelength = randomfile. length (); // start position of the read object int beginindex = (filelength> 4 )? 4: 0; // move the start position of the read file to the beginindex position. Randomfile. seek (beginindex); byte [] bytes = new byte [10]; int byteread = 0; // read 10 bytes at a time. If the file content is less than 10 bytes, read the remaining bytes. // Assign the number of bytes read at a time to byteread while (byteread = randomfile. Read (bytes ))! =-1) {system. Out. Write (bytes, 0, byteread) ;}} catch (ioexception e) {e. printstacktrace () ;}finally {If (randomfile! = NULL) {try {randomfile. close ();} catch (ioexception E1) {}}}/** display the remaining bytes in the input stream */Private Static void showavailablebytes (inputstream in) {try {system. out. println ("number of bytes in the Current byte input stream:" + in. available ();} catch (ioexception e) {e. printstacktrace () ;}} public static void main (string [] ARGs) {string filename = "C:/temp/newtemp.txt"; readfromfile. readfilebybytes (filename); readfromfile. read Filebychars (filename); readfromfile. readfilebylines (filename); readfromfile. readfilebyrandomaccess (filename) ;}} 5. append the content to the end of the file. Public class appendtofile {/*** a method: Use randomaccessfile */public static void appendmethoda (string filename, string content) {try {// open a random file stream, read and write randomaccessfile randomfile = new randomaccessfile (filename, "RW"); // file length, long filelength = randomfile. length (); // Move the Write File pointer to the end of the file. Randomfile. seek (filelength); randomfile. writebytes (content); randomfile. close ();} catch (ioexception e) {e. printstacktrace () ;}}/*** Method B: Use filewriter */public static void appendmethodb (string filename, string content) {try {// open a file writer. The second parameter in the constructor, true, indicates that the file is written as an append. filewriter writer = new filewriter (filename, true); writer. write (content); writer. close ();} catch (ioexception e) {e. printsta Cktrace () ;}} public static void main (string [] ARGs) {string filename = "C:/temp/newtemp.txt"; string content = "New append! "; // Append the file appendtofile by method. appendmethoda (filename, content); appendtofile. appendmethoda (filename, "APPEND end. \ n "); // display the file content readfromfile. readfilebylines (filename); // append the file appendtofile by method B. appendmethodb (filename, content); appendtofile. appendmethodb (filename, "APPEND end. \ n "); // display the file content readfromfile. readfilebylines (filename );}}

II,
Summary 2
Import Java. io. bufferedreader; import Java. io. file; import Java. io. filereader; import Java. io. filewriter; public class txtfile {public void read () {filereader Fr = NULL; bufferedreader BR = NULL; try {Fr = new filereader ("F: // a.txt "); BR = new bufferedreader (FR); string line = BR. readline (); While (line! = NULL) {system. out. println (line); line = BR. readline () ;}} catch (exception e) {system. out. println (E);} finally {try {If (BR! = NULL) Br. Close (); If (fr! = NULL) Fr. close (); // close the file} catch (exception e) {system. out. println (e) ;}}public void write () {file = NULL; filewriter fw = NULL; try {file = new file ("F: // a.txt "); FW = new filewriter (File); For (INT I = 0; I <20; I ++) {FW. append ("no." + I + 1 + "times") ;}} catch (exception e) {system. out. println (E);} finally {try {If (FW! = NULL) FW. Close (); // close the file} catch (exception e) {system. Out. println (e );}}}}

III,

Java file read/write Summary 3 efficiency test of each method

Read files:

Fileinputstream
Create a fileinputstream by opening a connection to the actual file.

Name. Create a new filedescriptor object to indicate the file connection.
Inputstreamreader
Inputstreamreader is a bridge between byte streams: it uses the specified charset to read bytes and decode them into words.

. The character set used can be specified by the name or explicitly specified. Otherwise, the default Character Set of the platform may be accepted.
Bufferedreader
Read text from the character input stream, buffer each character, so as to provide efficient reading of characters, arrays and rows. You can specify a buffer.

Or use the default size. In most cases, the default value is large enough.
Stringbuffer
A variable string of thread-safe characters. A string buffer similar to a string, but cannot be modified. Although at any point in time

It contains a specific character sequence, but the length and content of the sequence can be changed by calling some methods.

Public static void main (string [] ARGs) {// Read File Content File A = new file ("C:/add2.txt"); if (. 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:

 Fileoutputstream and filewriter are usually used to write files in Java. filewriter can only write text files. Fileoutputstream is often combined with bufferedoutputstream. In actual applications, most text files are written. So the following test uses three different methods to generate a file of the same number of rows and the same size.
   

Import Java. io. file; import Java. io. fileoutputstream; import Java. io. *; public class filetest {publicfiletest () {} publicstatic void main (string [] ARGs) {fileoutputstream out = NULL; fileoutputstream outstr = NULL; bufferedoutputstream buff = NULL; filewriter fw = NULL; int COUNT = 1000; // number of lines written to the file 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) + ""); 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) + "haoxi"); fw = new filewriter ("C:/add2.txt"); long begin3 = system. currenttimemillis (); For (INT I = 0; I <count; I ++) {FW. write ("test Java file operation \ r \ n");} FW. close (); long end3 = system. currenttimemillis (); system. out. println ("filewriter execution time:" + (end3-begin3) + "");} catch (exception e) {e. printstacktrace ();} finally {try {FW. close (); buff. close (); outstr. close (); out. close ();} catch (exception e) {e. printstacktrace ();}}}}

The following results are executed several times and the common data is retrieved. Because they are simple and compared, no detailed statistics are made.

1. When Count = 1000, that is, when writing 1000 lines of a file, the size of the file written is 18.5kb:
Fileoutputstream execution time: 46 Hao seconds
Bufferedoutputstream execution time: 31 Hao seconds
Filewriter execution time: 15 seconds

2. When Count = 10000, that is, when writing 10000 lines of a file, the size of the file written is KB:
Fileoutputstream execution Duration: 188 seconds
Bufferedoutputstream execution time: 32 Hao seconds
Filewriter execution time: 16 seconds

 

3. When Count = 100000, that is, when writing 100000 rows of files, the size of the written files is 1856kb:
Fileoutputstream execution Duration: 1266 seconds
Bufferedoutputstream execution time: 125 seconds
Filewriter execution time: 93 seconds

 

4. When Count = 1000000, that is, when writing 1000000 lines of a file, the size of the file written is 18555kb:
Fileoutputstream execution Duration: 12063 seconds
Bufferedoutputstream execution time: 1484 seconds
Filewriter execution time: 969 seconds

   From the above data, we can see that if bufferedoutputstream does not need to buffer the stream, the robustness of fileoutputstream writing files is very bad. When writing 1000000 rows of files, fileoutputstream is 11094 milliseconds slower than filewriter (11 seconds), and bufferedoutputstream is 515 milliseconds slower than filewriter.
   Do not underestimate the time of these seconds. When the amount of data operated is large, this performance gap will be very large. When the general data migration tool exports tens of millions of records from the database to generate SQL script files, the performance may differ by more than 10 minutes.

IV,

Create folders and files in Java

Package test; import Java. io. file; import Java. io. ioexception; public class createfiletest {/*** create a single file * @ Param destfilename file name * @ return returns true if the file is created successfully; otherwise, returns false */public static Boolean createfile (string destfilename) {file = new file (destfilename); If (file. exists () {system. out. println ("Creating a single file" + destfilename + "failed. The target file already exists! "); Return false;} If (destfilename. endswith (file. separator) {system. out. println ("Creating a single file" + destfilename + "failed. The target cannot be a directory! "); Return false;} If (! File. getparentfile (). exists () {system. Out. println ("The path of the target file does not exist. You are about to create a file... "); If (! File. getparentfile (). mkdirs () {system. Out. println ("An error occurred while creating the directory where the directory file is located! "); Return false ;}}// create the target file try {If (file. createnewfile () {system. out. println ("Creating a single file" + destfilename + "successful! "); Return true;} else {system. Out. println (" Creating a single file "+ destfilename +" failed! "); Return false ;}} catch (ioexception e) {e. printstacktrace (); system. Out. println (" Creating a single file "+ destfilename +" failed! "); Return false;}/*** create directory * @ Param destdirname target directory name * @ return returns true if the directory is created successfully, otherwise, false */public static Boolean createdir (string destdirname) {file dir = new file (destdirname); If (dir. exists () {system. out. println ("creating directory" + destdirname + "failed. The target directory already exists! "); Return false;} If (! Destdirname. endswith (file. separator) destdirname = destdirname + file. separator; // create a single directory if (dir. mkdirs () {system. out. println ("creating directory" + destdirname + "successful! "); Return true;} else {system. Out. println (" create directory "+ destdirname +" successful! "); Return false ;}} /*** create a temporary file * @ Param prefix the prefix of the temporary file * @ Param suffix the suffix of the temporary file * @ Param dirname the directory where the temporary file is located. If the input is null, then, create a temporary file * @ return under the user's document directory. After the temporary file is successfully created, return the standard path name string of the abstract path. Otherwise, return NULL */public static string createtempfile (string prefix, string suffix, string dirname) {file tempfile = NULL; try {If (dirname = NULL) {// create a temporary file tempfile = file in the default folder. createtempfile (prefix, suffix); Return tempfile. GETC Anonicalpath ();} else {file dir = new file (dirname); // If the directory of the temporary file does not exist, create if (! Dir. exists () {If (! Createfiletest. createdir (dirname) {system. Out. println ("Creating a temporary file failed. The directory where the temporary file cannot be created! "); Return NULL ;}} tempfile = file. createtempfile (prefix, suffix, DIR); return tempfile. getCanonicalPath () ;}} catch (ioexception e) {e. printstacktrace (); system. out. println ("failed to create temporary file" + E. getmessage (); return NULL ;}} public static void main (string [] ARGs) {// create the directory string dirname = "D:/test/test0/test1 "; createfiletest. createdir (dirname); // create the file string filename = dirname + "/Test2/testfile.txt"; createfiletest. createfile (filename); // create a temporary file string prefix = "Temp"; string suffix = ". TXT "; for (INT I = 0; I <10; I ++) {system. out. println ("temporary file created:" + createfiletest. createtempfile (prefix, suffix, dirname ));}}}

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.