Java read-write file encyclopedia

Source: Internet
Author: User
Tags ming

Using Java to manipulate text files is explained in detail
Abstract: Initially Java does not support the processing of text files, in order to compensate for this shortcoming introduced the reader and writer two classes
Originally Java is not support for the processing of text files, in order to compensate for this shortcoming introduced reader and writer two classes, these two classes are abstract class, writer write (char[] ch,int off,intlength), flush () and the Close () method as an abstract method, reader read (char[] ch,int off,int length) and the Close () method are abstract methods.  Subclasses should implement them separately. When we read and write text files, it is very convenient to use reader, for example Filereader,inputstreamreader and BufferedReader. The most important class is InputStreamReader, which is a bridge in which bytes are converted to characters. You can specify the encoding method in the constructor, assuming that the default encoding of the underlying operating system, such as GBK, will be used. When using FileReader to read files.<textarea cols="50" rows="15" name="code" class="java">FileReader fr = new FileReader ("Ming.txt"); int ch = 0;while ((ch = fr.read ())!=-1) {System.out.print ((char) ch);}</textarea>
The Read () method returns the next character. Of course you can also use Read (char[] ch,int off,int length) This is similar to processing binary files, not much. Suppose you use InputStreamReader to read a file while ((ch = isr.read ())!=-1)
{
System.out.print ((char) ch);
}
There is no difference between this and filereader, in fact, in the FileReader method is inherited from the InputStreamReader. The read () method is relatively time-consuming, assuming that in order to improve efficiency we can use BufferedReader to package reader, which can improve the read speed, we can read the text in one line 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 explicitly read a text file using reader, it is easy to write the file in writer. It is important to note that when you write a file, the data that is written is put into the buffer and then written to the file in order to improve efficiency. So there are times when you need to call the flush () method actively. The corresponding method for writing the file is:
<textarea cols="50" rows="15" name="code" class="java:showcolumns">FileWriter fw = new FileWriter ("Hello.txt"); String s = "Hello World"; Fw.write (S,0,s.length ()); Fw.flush (); OutputStreamWriter OSW = new OutputStreamWriter (new FileOutputStream ("Hello2.txt")); Osw.write (S,0,s.length ()); Osw.flush (); PrintWriter pw = new PrintWriter (new OutputStreamWriter (New FileOutputStream ("Hello3.txt"), True);p w.println (s);</textarea>
Don't forget to close the stream after you run out! Here is a sample to help beginners understand. In fact, sometimes the IO system of Java needs us to remember more, otherwise the day will be unfamiliar.
Import java.io.*;p ublic class testfile2{public static void Main (string[] args) throws Ioexception{filereader fr = new File  Reader ("Ming.txt"); char[] buffer = new Char[1024];int ch = 0;while ((ch = fr.read ())!=-1) {System.out.print ((char) ch);} InputStreamReader ISR = new InputStreamReader (New FileInputStream ("Ming.txt")), while ((ch = isr.read ())!=-1) {  System.out.print ((char) ch);} BufferedReader br = new BufferedReader (new InputStreamReader (New FileInputStream ("Ming.txt"));  String data = null;while (data = Br.readline ())!=null) {System.out.println (data);} FileWriter FW = new FileWriter ("Hello.txt");  String s = "Hello World"; Fw.write (S,0,s.length ()); Fw.flush (); OutputStreamWriter OSW = new OutputStreamWriter (New FileOutputStream ("Hello2.txt")); Osw.write (S,0,s.length ()); O  Sw.flush ();  PrintWriter pw = new PrintWriter (new OutputStreamWriter (New FileOutputStream ("Hello3.txt"), True);p w.println (s); Fr.close (); Isr.close (); Br.close (); Fw.close (); Osw.close ();p w.close ();}}

Read files in multiple ways in Java
One or more ways to read the contents of a file.
1, read file contents by byte
2, read file contents by character
3, read file contents by line
4, read file contents randomly

Import Java.io.bufferedreader;import java.io.file;import Java.io.fileinputstream;import Java.io.FileReader;import Java.io.ioexception;import Java.io.inputstream;import Java.io.inputstreamreader;import Java.io.RandomAccessFile; Import Java.io.reader;public class ReadFromFile {/*** reads files in bytes, often used for reading binary files, slices, sounds, images, etc. * The name of the @param filename file */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, reads one byte at a time:");//read one byte 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 ("reads the contents of the file in bytes, reads multiple bytes at a time:");//Read multiple bytes at a time byte[] tempbytes = new Byte[100];int Byteread = 0;in = new file InputStream (FileName); Readfromfile.showavailablebytes (in);//Read into 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) {}}}}/*** reads the file in characters, often used for reading text, numbers, and other types of files * @param fileName File name */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, reads 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, RN these two characters are together, representing a newline. But assuming that the two characters are displayed separately, the lines are changed two times. So, shield off 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 multiple bytes at a time:");//Read more than one character at a time char[] tempchars = new Char[30];int Charread = 0;reader = new I Nputstreamreader (new FileInputStream);//reads multiple characters into a character array, charread the number of characters at a time while (Charread = Reader.read ( Tempchars)!=-1) {//same shield off 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 behavior unit, often used to read a row-oriented format file * @param file Name */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 the behavior unit, reads a whole line at a time:"); reader = new BufferedReader (New FileReader (file)); String tempstring = Null;int line = 1;//reads one row at a time until NULL is read into the file end 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 * @param fileName file name */public static void readfilebyrandomaccess (String filename) {randomaccessfile Randomfile = null;try {System.out.println ("Random reading of a file content:");//Open a random interviewFile stream, 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;//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, assuming that the contents of the file are less than 10 bytes, read the remaining bytes. Assigns the number of bytes read to Bytereadwhile ((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 * @param in*/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);}} Append the content to the end of the file import java.io. Filewriter;import java.io.ioexception;import java.io.randomaccessfile;/*** Append the content to the end of the file */public class AppendToFile {/* * * A method Append file: Use randomaccessfile* @param filename File name * @param content appended */public static void Appendmethoda (String Filena Me,string content) {try {//Open a random Access file stream, read and write Randomaccessfile randomfile = new Randomaccessfile (fileName, "RW");//File length, 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 ();}} /*** B method Append file: Use filewriter* @param filename* @param content*/public static void Appendmethodb (String fileName, String cont ENT) {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 by method A (FileName, contENT); 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-write file encyclopedia

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.