[Java] Read file method Daquan

Source: Internet
Author: User

1. read file contents by byte
2. read file contents by character
3. Read the contents of the file by line

4. Random reading of file contents

 Public classReadFromFile {/*** Read files in bytes, often used to read binary files, slices, sounds, images, and other files. */     Public Static voidreadfilebybytes (String fileName) {File file=NewFile (fileName); InputStream in=NULL; Try{System.out.println ("reads the contents of the file in bytes, one byte at a time:"); //read one byte at a timein =Newfileinputstream (file); intTempbyte;  while((Tempbyte = In.read ())! =-1) {System.out.write (tempbyte);        } in.close (); } Catch(IOException e) {e.printstacktrace (); return; }        Try{System.out.println ("Read the contents of the file in bytes, read multiple bytes at a time:"); //read multiple bytes at a time            byte[] Tempbytes =New byte[100]; intByteread = 0; Inch=NewFileInputStream (fileName);            Readfromfile.showavailablebytes (in); //reads in multiple bytes into a byte array, Byteread is the number of bytes read in 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) {}}} }    /*** Read files in characters, commonly used for reading text, numbers and other types of files*/     Public Static voidreadfilebychars (String fileName) {File file=NewFile (fileName); Reader Reader=NULL; Try{System.out.println ("reads the contents of the file in characters, one byte at a time:"); //read one character at a timeReader =NewInputStreamReader (Newfileinputstream (file)); intTempchar;  while((Tempchar = Reader.read ())! =-1) {                //for Windows, \ r \ n These two characters are together, representing a newline. //However, if the two characters are displayed separately, the lines are changed two times. //therefore, block \ r, or block \ n. Otherwise, there will be a lot more empty rows.                 if(((Char)! = ' \ r ' Tempchar) {System.out.print (Char) Tempchar);        }} reader.close (); } Catch(Exception e) {e.printstacktrace (); }        Try{System.out.println ("Read the contents of the file in characters, read multiple bytes at a time:"); //read multiple characters at once            Char[] Tempchars =New Char[30]; intCharread = 0; Reader=NewInputStreamReader (NewFileInputStream (fileName)); //Reads multiple characters into a character array, charread the number of characters to read at a time             while((Charread = Reader.read (tempchars))! =-1) {                //also shield off \ R does not show                if(Charread = =tempchars.length)&& (tempchars[tempchars.length-1]! = ' \ r ') {System.out.print (tempchars); } Else {                     for(inti = 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) {}}} }    /*** Read files in behavioral units, often used to read line-oriented format files*/     Public Static voidreadfilebylines (String fileName) {File file=NewFile (fileName); BufferedReader Reader=NULL; Try{System.out.println ("Read the contents of the file in the behavior unit and read the entire line at a time:"); Reader=NewBufferedReader (Newfilereader (file)); String tempstring=NULL; intline = 1; //read one line at a time until NULL is read to the end of the file             while((tempstring = Reader.readline ())! =NULL) {                //Show Line NumbersSystem.out.println ("line" + Line + ":" +tempstring); Line++;        } reader.close (); } Catch(IOException e) {e.printstacktrace (); } finally {            if(Reader! =NULL) {                Try{reader.close (); } Catch(IOException E1) {}}} }    /*** Random reading of file contents*/     Public Static voidreadfilebyrandomaccess (String fileName) {randomaccessfile randomfile=NULL; Try{System.out.println ("Random reading of a file content:"); //open a random Access file stream as read-onlyRandomfile =NewRandomaccessfile (FileName, "R"); //file length, number of bytes            LongFilelength =randomfile.length (); //the starting position of the read file            intBeginindex = (Filelength > 4)? 4:0; //moves the start position of the read file to the Beginindex location. Randomfile.seek (Beginindex); byte[] bytes =New byte[10]; intByteread = 0; //read 10 bytes at a time, or read the remaining bytes if the contents of the file are less than 10 bytes. //assigns the number of bytes read 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) {}}} }    /*** Shows the number of bytes remaining in the input stream*/    Private Static voidshowavailablebytes (InputStream in) {Try{System.out.println ("The number of bytes in the current byte input stream is:" +in.available ()); } Catch(IOException e) {e.printstacktrace (); }    }     Public Static voidMain (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 classAppendtofile {/*** A method Append file: Use Randomaccessfile*/     Public Static voidAppendmethoda (String fileName, string content) {Try {            //open a random Access file stream, read and writeRandomaccessfile Randomfile =NewRandomaccessfile (FileName, "RW"); //file length, number of bytes            LongFilelength =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 (); }    }    /*** B method Append file: Use FileWriter*/     Public Static voidAppendmethodb (String fileName, string content) {Try {            //open a write file, the second parameter in the constructor true indicates that the file is written in append formFileWriter writer =NewFileWriter (FileName,true);            Writer.write (content);        Writer.close (); } Catch(IOException e) {e.printstacktrace (); }    }     Public Static voidMain (string[] args) {String fileName= "C:/temp/newtemp.txt"; String content= "New append!"; //append files by method aAppendtofile.appendmethoda (fileName, content); Appendtofile.appendmethoda (FileName,"Append end." \ n "); //Show file ContentsReadfromfile.readfilebylines (fileName); //Append files by method BAppendtofile.appendmethodb (fileName, content); Appendtofile.appendmethodb (FileName,"Append end." \ n "); //Show file ContentsReadfromfile.readfilebylines (fileName); }}

Excerpted from http://www.cnblogs.com/lovebread/archive/2009/11/23/1609122.html

[Java] Read file method Daquan

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.