Detailed description of Java operations on text files

Source: Internet
Author: User

 

 

At first, Java does not support text file processing. In order to make up for this defect, two classes, reader and writer, are introduced. These two classes are abstract classes. In writer, write (char [] CH, int off, int
Length), flush () and close () are abstract methods. In reader, read (char [] CH, int off, int length) and close () are abstract methods. Subclass should implement them separately.
When reading and writing text files, It is very convenient to use reader, such as filereader, inputstreamreader, and bufferedreader. The most important class is inputstreamreader,
It is a bridge between byte conversion and character conversion. You can specify the encoding method in the constructor. If you do not specify the encoding method, the underlying operating system uses the default encoding method, such as GBK. When filereader is used to read files
.

The read () method returns the read to get the next character. Of course, you can also use read (char [] CH, int off, int length), which is similar to processing binary files. If you use
When inputstreamreader reads files
While (CH = ISR. Read ())! =-1)
{
System. Out. Print (char) CH );
}
This is no different from filereader. In fact, the methods in filereader are inherited from inputstreamreader. The read () method is time-consuming.
We can use bufferedreader to wrap the reader, which can improve the read speed. We can read a row of text and use the Readline () method.
Bufferedreader BR = new bufferedreader (New inputstreamreader (New fileinputstream ("ming.txt ")));
String data = NULL;
While (Data = Br. Readline ())! = NULL)
{
System. Out. println (data );
}
When you understand how to use reader to read text files, it is also very easy to use writer to write files. Note that when you write a file, the data you write will first
Put in the buffer, and then write the file. So sometimes you need to actively call the flush () method.

Don't forget to close the stream after it is used up! Code:

Public class txtoprdemo {<br/> Public static void main (string [] ARGs) throws ioexception {</P> <p> // use filereader to read files <br/> filereader Fr = new filereader ("ming.txt"); <br/> int CH = 0; <br/> // The read () method returns the read to get the next character <br/> while (CH = Fr. read ())! =-1) {<br/> system. out. print (char) CH); <br/>}</P> <p> // inputstreamreader reads the file, there is no difference with filereader <br/> inputstreamreader ISR = new inputstreamreader (New fileinputstream (<br/> "ming.txt"); <br/> while (CH = ISR. read ())! =-1) {<br/> system. out. print (char) CH); <br/>}</P> <p> // use bufferedreader to wrap the reader, this improves the read speed <br/> bufferedreader BR = new bufferedreader (New inputstreamreader (<br/> New fileinputstream ("ming.txt "))); <br/> string data = NULL; <br/> // read text in one row, using the Readline () method <br/> while (Data = BR. readline ())! = NULL) {<br/> system. out. println (data); <br/>}</P> <p> filewriter fw = new filewriter ("hello.txt"); <br/> string S = "Hello World "; <br/> FW. write (S, 0, S. length (); <br/> // when writing a file, to improve the efficiency, the written data is first placed in the buffer zone and then written to the file. Therefore, you must call the flush () method. <Br/> FW. flush (); </P> <p> outputstreamwriter OSW = new outputstreamwriter (New fileoutputstream (<br/> "hello2.txt"); <br/> OSW. write (S, 0, S. length (); <br/> // when writing a file, to improve the efficiency, the written data is first placed in the buffer zone and then written to the file. Therefore, you must call the flush () method. <Br/> OSW. flush (); </P> <p> printwriter PW = new printwriter (New outputstreamwriter (<br/> New fileoutputstream ("hello3.txt"), true ); <br/> PW. println (s); </P> <p> // close the stream <br/> Fr. close (); <br/> ISR. close (); <br/> Br. close (); <br/> FW. close (); <br/> OSW. close (); <br/> PW. close (); <br/>}< br/>}

 

 

Multiple methods of reading files in Java
1. Read File Content in multiple ways.
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 {<br/>/** <br/> * reads files in bytes. It is often used to read binary files, files, sounds, images, and other files. <Br/> * @ Param filename <br/> * file name <br/> */<br/> Public static void readfilebybytes (string filename) {<br/> file = new file (filename); <br/> inputstream in = NULL; <br/> try {<br/> system. out. println ("Read File Content in bytes, one byte at a time :"); <br/> // read one byte at a time <br/> In = new fileinputstream (File); <br/> int tempbyte; <br/> while (tempbyte = in. read ())! =-1) {<br/> system. out. write (tempbyte); <br/>}< br/> in. close (); <br/>}catch (ioexception e) {<br/> E. printstacktrace (); <br/> return; <br/>}</P> <p> try {<br/> system. out. println ("Read File Content in bytes, read multiple bytes at a time :"); <br/> // read multiple bytes at a time <br/> byte [] tempbytes = new byte [100]; <br/> int byteread = 0; <br/> In = new fileinputstream (filename); <br/> readfromfile. showavailablebytes (in); <br/> // read multiple bytes into the byte array. byteread is the word read at a time. Number of nodes <br/> while (byteread = in. Read (tempbytes ))! =-1) {<br/> system. out. write (tempbytes, 0, byteread); <br/>}< br/>} catch (exception E1) {<br/> e1.printstacktrace (); <br/>} finally {<br/> If (in! = NULL) {<br/> try {<br/> in. close (); <br/>} catch (ioexception E1) {<br/>}< br/>/** <br/> * reads a file in characters, it is often used to read text, files of numbers and other types <br/> * @ Param filename <br/> * file name <br/> */<br/> Public static void readfilebychars (string filename) {<br/> file = new file (filename); <br/> reader = NULL; <br/> try {<br/> system. out. println ("Read File Content in characters, one byte at a time:"); <br/> // read one character at a time <br/> r Eader = new inputstreamreader (New fileinputstream (File); <br/> int tempchar; <br/> while (tempchar = reader. Read ())! =-1) {<br/> // for Windows, when the RN characters are together, a line break is displayed. <Br/> // if the two characters are displayed separately, the rows are changed twice. <Br/> // Therefore, block R or N. Otherwise, there will be a lot more blank lines. <Br/> If (char) tempchar )! = 'R') {<br/> system. out. print (char) tempchar); <br/>}< br/> reader. close (); <br/>}catch (exception e) {<br/> E. printstacktrace (); <br/>}< br/> try {<br/> system. out. println ("Read File Content in characters, multiple bytes read at a time :"); <br/> // read multiple characters at a time <br/> char [] tempchars = new char [30]; <br/> int charread = 0; <br/> reader = new inputstreamreader (New fileinputstream (filename); <br/> // read multiple characters into the character array, charread is the number of characters read at a time <br/> while (Charread = reader. Read (tempchars ))! =-1) {<br/> // If (charread = tempchars. length) <br/> & (tempchars [tempchars. length-1]! = 'R') {<br/> system. out. print (tempchars); <br/>}else {<br/> for (INT I = 0; I <charread; I ++) {<br/> If (tempchars [I] = 'R') {<br/> continue; <br/>} else {<br/> system. out. print (tempchars [I]); <br/>}< br/>} catch (exception E1) {<br/> e1.printstacktrace (); <br/>}finally {<br/> If (reader! = NULL) {<br/> try {<br/> reader. close (); <br/>} catch (ioexception E1) {<br/>}< br/>/** <br/> * read files in behavior units, commonly used to read row-oriented formatted files <br/> * @ Param filename <br/> * file name <br/> */<br/> Public static void readfilebylines (string filename) {<br/> file = new file (filename); <br/> bufferedreader reader = NULL; <br/> try {<br/> system. out. println ("read the file content in the unit of action, one whole row at a time:"); <br/> reader = N EW bufferedreader (New filereader (File); <br/> string tempstring = NULL; <br/> int line = 1; <br/> // read a row at a time, until the end of reading null is the file <br/> while (tempstring = reader. readline ())! = NULL) {<br/> // display the row number <br/> system. out. println ("line" + LINE + ":" + tempstring); <br/> line ++; <br/>}< br/> reader. close (); <br/>}catch (ioexception e) {<br/> E. printstacktrace (); <br/>}finally {<br/> If (reader! = NULL) {<br/> try {<br/> reader. close (); <br/>} catch (ioexception E1) {<br/>}< br/>/** <br/> * Randomly Read File content <br/> * <br/> * @ Param filename <br/> * file name <br/> */<br/> Public static void readfilebyrandomaccess (string filename) {<br/> randomaccessfile randomfile = NULL; <br/> try {<br/> system. out. println ("randomly read a file:"); <br/> // open a random access file stream in read-only mode <br/> randomfile = new randomaccessfi Le (filename, "R"); <br/> // file length, number of bytes <br/> long filelength = randomfile. length (); <br/> // start position of the file to be read <br/> int beginindex = (filelength> 4 )? 4: 0; <br/> // move the start position of the read file to the beginindex position. <Br/> randomfile. seek (beginindex); <br/> byte [] bytes = new byte [10]; <br/> int byteread = 0; <br/> // read 10 bytes at a time. If the file content is less than 10 bytes, read the remaining bytes. <Br/> // assign the number of bytes read at a time to byteread <br/> while (byteread = randomfile. Read (bytes ))! =-1) {<br/> system. out. write (bytes, 0, byteread); <br/>}< br/>} catch (ioexception e) {<br/> E. printstacktrace (); <br/>}finally {<br/> If (randomfile! = NULL) {<br/> try {<br/> randomfile. close (); <br/>} catch (ioexception E1) {<br/>}< br/>/** <br/> * display the remaining bytes in the input stream count <br/> * @ Param in <br/> */<br/> Private Static void showavailablebytes (inputstream in) {<br/> try {<br/> system. out. println ("number of bytes in the Current byte input stream:" + in. available (); <br/>} catch (ioexception e) {<br/> E. printstacktrace (); <br/>}< br/> Public static void main (string [] ARGs) {<br/> string filename = "C: /temp/newtemp.txt "; <br/> readfromfile. readfilebybytes (filename); <br/> readfromfile. readfilebychars (filename); <br/> readfromfile. readfilebylines (filename); <br/> readfromfile. readfilebyrandomaccess (filename); <br/>}< br/>}

 

 

2. append the content to the end of the file

 

Public class appendtofile {<br/>/** <br/> * method: use randomaccessfile <br/> * @ Param filename <br/> * file name <br/> * @ Param content <br/> * Append content <br/> */<br/> Public static void appendmethoda (string filename, string content) {<br/> try {<br/> // open a random access file stream, in read/write mode <br/> randomaccessfile randomfile = new randomaccessfile (filename, "RW"); <br/> // file length, number of bytes <br/> long filelength = randomfile. lengt H (); <br/> // move the Write File pointer to the end of the file. <Br/> randomfile. seek (filelength); <br/> randomfile. writebytes (content); <br/> randomfile. close (); <br/>}catch (ioexception e) {<br/> E. printstacktrace (); <br/>}< br/>/** <br/> * method B append a file: use filewriter <br/> * @ Param filename <br/> * @ Param content <br/> */<br/> Public static void appendmethodb (string filename, string content) {<br/> try {<br/> // open a file writer. The second parameter in the constructor is true, indicating that the file is written as an append. <br/> Filewriter writer = new filewriter (filename, true); <br/> writer. write (content); <br/> writer. close (); <br/>}catch (ioexception e) {<br/> E. printstacktrace (); <br/>}< br/> Public static void main (string [] ARGs) {<br/> string filename = "C: /temp/newtemp.txt "; <br/> string content =" New append! "; <Br/> // append a file by method A <br/> appendtofile. appendmethoda (filename, content); <br/> appendtofile. appendmethoda (filename, "APPEND end. N "); <br/> // display the file content <br/> readfromfile. readfilebylines (filename); <br/> // append the file by Method B <br/> appendtofile. appendmethodb (filename, content); <br/> appendtofile. appendmethodb (filename, "APPEND end. N "); <br/> // display the file content <br/> readfromfile. readfilebylines (filename); <br/>}< br/>}

 

 

3. Read byte files to byte Arrays

Public class readfiletobytearray {<br/> // returns the file byte to the byte array <br/> Public static byte [] getbytesfromfile (File file) throws ioexception {<br/> inputstream is = new fileinputstream (File); <br/> // obtain the file length <br/> long length = file. length (); <br/> // an array of long type cannot be used. <br/> // an array of the long type needs to be int type. <br/> // ensure the file size before converting it into an int type. greater than integer. max_value. <br/> If (length> integer. max_value) {<br/> // if the file size is too large <br/>}< br/> // create a byte array to save data <br/> byte [] bytes = new byte [( INT) length]; <br/> // read byte <br/> int offset = 0; <br/> int numread = 0; <br/> while (offset <bytes. length <br/> & (numread = is. read (bytes, offset, bytes. length-offset)> = 0) {<br/> Offset + = numread; <br/>}< br/> // make sure all bytes are read <br/> If (offset <bytes. length) {<br/> throw new ioexception ("cocould not completely Read File" <br/> + file. getname (); <br/>}< br/> // closes the input stream and returns bytes <br/> is. close (); <br/> return bytes; <br/>}< br/>}

 

 

 

 

 

 

 

 

 

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.