"Go" [Java] Read file methods Daquan __java

Source: Internet
Author: User

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

4, Random Read the contents of the file

public class ReadFromFile {/** * reads files in bytes and is often used to read binary files, such as pictures, sounds, images, and so on.
        */public static void Readfilebybytes (String filename) {File File = new file (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 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 the contents of the file 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); Reads multiple bytes into a byte array, byteread the number of bytes read at a while ((Byteread = In.read (tempbytes))!=-1) {SyStem.out.write (tempbytes, 0, Byteread);
        } catch (Exception E1) {e1.printstacktrace ();
                Finally {if (in!= null) {try {in.close ();
     The catch (IOException E1) {}}}/** * reads files in characters, often used to read text, numbers, and other types of files
        */public static void Readfilebychars (String filename) {File File = new file (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 time reader = new InputStreamReader (new FileInputStream (file));
            int Tempchar;
                while ((Tempchar = Reader.read ())!=-1) {//for Windows, \ r \ n These two characters together indicate a newline.
                However, if the two characters are displayed separately, the lines will be changed two times. So, block \ r, or block \ n.
                Otherwise, there will be a lot more empty lines.
               if ((char) tempchar)!= ' \ R ') {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 a time char[] Tempchars = new CHAR[30];
            int charread = 0;
            reader = new InputStreamReader (fileName) (new FileInputStream); Reads more than one character into an array of characters, charread as the number of read characters while (Charread = Reader.read (tempchars))!=-1) {//the same screen off \ R does not display 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]);
 }
                    }               A catch (Exception E1) {e1.printstacktrace ();
                finally {if (reader!= null) {try {reader.close (); 
    The catch (IOException E1) {}}}/** * Reads a file in a behavior unit and is often used to read a line-oriented format file.
        public static void Readfilebylines (String filename) {File File = new file (fileName);
        BufferedReader reader = null;
            try {System.out.println ("reads the contents of the file in a unit of behavior, reads one whole line at a time:");
            reader = new BufferedReader (new FileReader (file));
            String tempstring = null;
            int line = 1;
                Read one row at a time until you read null for file end while ((tempstring = Reader.readline ())!= null) {//Show line 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) {}}}}/** * Random Read file content */Public STA
        tic void Readfilebyrandomaccess (String fileName) {randomaccessfile randomfile = null;
            try {System.out.println ("read the contents of a file randomly:");
            Open a random Access file stream, read-only randomfile = new Randomaccessfile (FileName, "R");
            File length, byte number long filelength = Randomfile.length (); Read the starting position of the file int beginindex = (Filelength > 4)?
            4:0;
            Moves the start position of the read file to the Beginindex location.
            Randomfile.seek (Beginindex);
            byte[] bytes = new BYTE[10];
            int byteread = 0;
            Read 10 bytes at a time and read the remaining bytes if the file content is less than 10 bytes. Assigns a read number of bytes 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 ();
    The catch (IOException E1) {}}}/** * Displays the number of bytes left in the input stream * * private static void Showavailablebytes (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 void Main (string[] args) {String fileName = ' c:/temp/newtemp.txt ';
        Readfromfile.readfilebybytes (FileName);
        Readfromfile.readfilebychars (FileName);
        Readfromfile.readfilebylines (FileName);
    Readfromfile.readfilebyrandomaccess (FileName);

 }
}

5. Append content to file tail

public class Appendtofile {/** * A method Append file: Using randomaccessfile/public static void Appendmethoda (String FileName, String content) {try {//Open a random Access file stream, read-write Randomaccessfile randomfile = new R
            Andomaccessfile (FileName, "RW");
            File length, byte number 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 ();  /** * B method Append file: Using FileWriter */public static void Appendmethodb (string fileName, string content)  {try {//Open a write-file, the second argument in the constructor is true to write the file in 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 = "C:/temp/newtemp.txt";
        String content = "New append!";
        Append file Appendtofile.appendmethoda (filename, content) by method A; Appendtofile.appendmethoda (FileName, "append end.")
        \ n ");
        Displays the contents of the file Readfromfile.readfilebylines (fileName);
        Append file Appendtofile.appendmethodb (filename, content) by method B; Appendtofile.appendmethodb (FileName, "append end.")
        \ n ");
    Displays the contents of the file Readfromfile.readfilebylines (fileName); }
}

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.