How Java io reads and writes files

Source: Internet
Author: User

Java abstracts the data of these different sources and targets into data streams; the Java language input and output functions are very powerful and flexible; In the Java class Library, the IO section is very large because it involves a wide range of fields: standard input and output, file manipulation, data flow on the network, string flow, Object flow, zip file stream.

Here are a few ways to read and write files:

First, InputStream, OutputStream (Byte stream)

//read file (Byte stream)InputStream in =NewFileInputStream ("D:\\1.txt");//write the appropriate fileOutputStream out =NewFileOutputStream ("D:\\2.txt");//reading Data//How many bytes are taken at oncebyte[] bytes =New byte[2048];//Accept the Read content (n represents the relevant data, but the form of a number)intn =-1;//Loop out Data while((n = in.read (bytes,0,bytes.length))! =-1) {    //Convert to StringString str =NewString (Bytes,0,n, "GBK");    #这里可以实现字节到字符串的转换, Comparative practical System.out.println (str); //Writing related filesOut.write (Bytes, 0, n);}//Close the streamin.close (); Out.close ();

Second, Bufferedinputstream, Bufferedoutputstream (cache byte stream) use the same way as the byte stream, but more efficient (recommended)

//read file (cache byte stream)Bufferedinputstream in =NewBufferedinputstream (NewFileInputStream ("D:\\1.txt"));//write the appropriate fileBufferedoutputstream out =NewBufferedoutputstream (NewFileOutputStream ("D:\\2.txt"));//reading Data//How many bytes are taken at oncebyte[] bytes =New byte[2048];//Accept the Read content (n represents the relevant data, but the form of a number)intn =-1;//Loop out Data while((n = in.read (bytes,0,bytes.length))! =-1) {    //Convert to StringString str =NewString (Bytes,0,n, "GBK");    System.out.println (str); //Writing related filesOut.write (Bytes, 0, n);}//Clear CacheOut.flush ();//Close the streamin.close (); Out.close ();

Third, InputStreamReader, OutputStreamWriter (byte stream, this way is not recommended, not directly read and write bytes). Use ranges for character conversions

//read file (Byte stream)InputStreamReader in =NewInputStreamReader (NewFileInputStream ("D:\\1.txt"), "GBK");//write the appropriate fileOutputStreamWriter out =NewOutputStreamWriter (NewFileOutputStream ("D:\\2.txt"));//reading Data//Loop out Databyte[] bytes =New byte[1024];intLen =-1; while(len = In.read ())! =-1) {System.out.println (len); //Writing related filesOut.write (len);}//Clear CacheOut.flush ();//Close the streamin.close (); Out.close ();

Iv. FileReader, FileWriter (provides a small amount of text reading and writing)

Try{    //Write a text file using the FileWriter classFileWriter writer=NewFileWriter (fileName); Writer.write ("Hello kuka:\n"); Writer.write ("My name is coolszy!\n"); Writer.write ("I like you and miss." "); Writer.close ();} Catch(IOException e) {e.printstacktrace ();}Try{    //Use the FileWriter class to append information to a text fileFileWriter writer =NewFileWriter (FileName,true); SimpleDateFormat format=NewSimpleDateFormat (); String Time= Format.format (NewDate ()); Writer.write ("\n\t" +Time ); Writer.close ();} Catch(IOException e) {e.printstacktrace ();}intC=0;Try{    //using the FileReader class to read a text fileFileReader reader=NewFileReader (fileName); C=Reader.read ();  while(C!=-1) {System.out.print (Char) c); C=Reader.read (); } reader.close ();} Catch(Exception e) {e.printstacktrace ();}

Five, BufferedReader, BufferedWriter (Cache stream, provides ReadLine method to read a line of text)

//Read file (character stream)BufferedReader in =NewBufferedReader (NewInputStreamReader (NewFileInputStream ("D:\\1.txt"), "GBK") ); #这里主要是涉及中文//BufferedReader in = new BufferedReader (New FileReader ("D:\\1.txt" ));//write the appropriate fileBufferedWriter out =NewBufferedWriter (NewOutputStreamWriter (NewFileOutputStream ("D:\\2.txt"), "GBK"));//BufferedWriter out = new BufferedWriter (New FileWriter ("D:\\2.txt"));//reading Data//Loop out DataString str =NULL; while(str = in.readline ())! =NULL) {System.out.println (str); //Writing related filesout.write (str);  Out.newline (); //Note that the line-wrapping effect does not necessarily occur on various computers
// Clear Cache  // Close Flow in.close (); Out.close ();

Six, Reader, PrintWriter (PrintWriter This is very useful, in writing data colleagues can format)

//read file (Byte stream)Reader in =NewInputStreamReader (NewFileInputStream ("D:\\1.txt"), "GBK");//write the appropriate filePrintWriter out =NewPrintWriter (NewFileWriter ("D:\\2.txt"));//reading Data//Loop out Databyte[] bytes =New byte[1024];intLen =-1; while(len = In.read ())! =-1) {System.out.println (len); //Writing related filesOut.write (len);}//Clear CacheOut.flush ();//Close the streamin.close (); Out.close ();

How Java io reads and writes files

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.