[Java] Read file

Source: Internet
Author: User

This article transferred from: http://www.cnblogs.com/lovebread/archive/2009/11/23/1609122.html

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 class ReadFromFile {/** * reads files in bytes and is commonly used for reading binary files, slices, sounds, images, and so on.        */public static void Readfilebybytes (String fileName) {File File = new file (fileName);        InputStream in = null;            try {System.out.println ("read the contents of the file in bytes, one byte at a time:");            Read one byte in = new FileInputStream (file) at a time;            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 more than one byte 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 into multiple bytes into a byte array, Byteread is the number of bytes read in while (Byteread = In.read (tempbytes))! =-1) {System.out.wri Te (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 */P        ublic static void Readfilebychars (String filename) {File File = new file (fileName);        Reader reader = null;            try {System.out.println ("read 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 represent a line break.                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) 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 more than one byte at a time:");            Read multiple characters at a time char[] Tempchars = new CHAR[30];            int charread = 0;            reader = new InputStreamReader (new FileInputStream (FileName)); Reads multiple characters into a character array, charread the number of characters at a time while (Charread = Reader.read (tempchars))! =-1) {//the same mask off \ r No  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) {}}}}/** * read files in the behavior unit, often used to read line-oriented format files */publ        IC static void Readfilebylines (String fileName) {File File = new file (fileName);        BufferedReader reader = null;            try {System.out.println ("reads the contents of the file in the behavior unit, reads a whole line at a time:");            reader = new BufferedReader (new FileReader (file));            String tempstring = null;            int line = 1;                Read one line at a time until NULL is read to the end of the file while ((tempstring = Reader.readline ()) = null) {//Display 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 contents */Public s        tatic void Readfilebyrandomaccess (String fileName) {randomaccessfile randomfile = null;            try {System.out.println ("Random reading of a file content:");            Open a random Access file stream, as read-only randomfile = new Randomaccessfile (FileName, "R");            File length, number of bytes 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, 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 (byte            S, 0, Byteread);        }} catch (IOException e) {e.printstacktrace (); } finally {if (randomfile! = null) {                try {randomfile.close (); } catch (IOException e1) {}}}}/** * shows the number of bytes left in the input stream */private static        void Showavailablebytes (InputStream in) {try {System.out.println ("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 the content to the end of the file

public class Appendtofile {/** * A method Append file: Use Randomaccessfile */public static void Appendmethoda (String file Name, String content) {try {//Open a random Access file stream, read and write Randomaccessfile randomfile = new Randomac            Cessfile (FileName, "RW");            File length, number of bytes 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: Use FileWriter */public static void Appendmethodb (string fileName, string content) {            try {//Open a write file, the second parameter in the constructor true indicates that the file is written 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 ");        Display file Contents Readfromfile.readfilebylines (fileName);        Append file Appendtofile.appendmethodb (fileName, content) by method B; Appendtofile.appendmethodb (FileName, "append end.        \ n ");    Display file Contents Readfromfile.readfilebylines (fileName); }}

  

[Java] Read file

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.