[Java] File Reading method and classification demo

Source: Internet
Author: User

Recently, there was a software function that needed to upload files. I was familiar with several methods of reading files from Java, which benefited a lot from the following content. Thanks to the author of the original article.

(Original address: http://www.cnblogs.com/lovebread/archive/2009/11/23/1609122.html,http://java.chinaitlab.com/base/835830.html)

I. Java file reading method:

1. fileinputstream class overview

Inheritance relationship:

Java. Io. fileinputstream-> JAVA. Io. inputstream-> JAVA. Lang. Object

Implementation Interface

Closeable

Class Functions

Fileinputstream obtains the input bytes from a file in the file system. Which files are available depends on the host environment.

Fileinputstream is used to read original byte streams such as data. To read the shard stream, consider using filereader.

2. attributes and behaviors of Classes

2.1 Public void close () throws ioexception

Function:

Close the input stream of this file and release all system resources related to this stream.

If the stream has a channel associated with it, the channel is closed.

Specified:

Close in interface closeable

Overwrite:

Close in inputstream

Throw:

Ioexception-if an I/O error occurs.

2.2 Public int read () throws ioexception

Function:

Read a Data byte from the input stream. If no input is available, this method is blocked.

Specified:

Read in inputstream

Return Value:

The next Data byte. If it has reached the end of the file,-1 is returned.

Throw:

Ioexception-if an I/O error occurs.

2.3 Public int read (byte [] B) throws ioexception

Function:

The input stream reads data of up to B. length bytes into a byte array. This method is blocked before some input is available.

Overwrite:

Read in inputstream

Parameters:

B-
Buffer for storing read data

Return Value:

The total number of bytes read into the buffer. If no more data has been reached the end of the file,-1 is returned.

Throw:

Ioexception-if an I/O error occurs.

2.4 public int read (byte [] B, int off, int Len) throws ioexception

Function:

The input stream reads data of up to len bytes into a byte array. This method is blocked before some input is available.

Overwrite:

Read in inputstream

Parameters:

B-
The buffer that stores the read data.

Off-the starting offset of the data.

Len-Maximum number of bytes read.

Return Value:

The total number of bytes read into the buffer. If no more data has been reached the end of the file,-1 is returned.

Throw:

Ioexception-if an I/O error occurs.

Ii. Demo and description:

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. readfilebychars (filename); readfromfile. readfilebylines (filename); readfromfile. readfilebyrandomaccess (filename );}}

5. append the content to the end of the file.

Public class appendtofile {/*** a method to append a file: Use randomaccessfile */public static void appendmethoda (string filename, string content) {try {// to open a random file stream, read/write randomaccessfile randomfile = new randomaccessfile (filename, "RW"); // file length, number of bytes 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 );}}

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.