Summary of Java I/O operations

Source: Internet
Author: User

Ching

Original address: http://blog.csdn.net/qingdujun/article/details/41154807


This article company explains FileWriter, FileReader, Bufferwriter, Bufferreader, Linenumreader, FileOutputStream, FileInputStream, Bufferinputstream, Bufferoutputstream and other flow operation technology.

——————————————————————————————————————————————————————

1, understand the "source" and "purpose":

Stream of Byte stream characters

Source (Input stream): InputStream (), Reader ();

Purpose (Output): OutputStream (), Reader ().

2, understand whether the data "plain text":

is: character stream;

No: Byte stream.

3, understand the detailed use of the object:

SOURCE device: Memory, hard disk, keyboard.

Purpose: Memory, hard disk, console.

——————————————————————————————————————————————————————

1. Write File FileWriter

The difference between flush () and close ():

1) Flush () flushes the stream, writes the data to the file, and the stream can be used;

2) Close () before closing the stream. Will voluntarily call flush () to flush the stream.

After closing. The stream cannot be used again.

Package Io.dol.sn;import Java.io.filewriter;import Java.io.ioexception;public class Filewriterdemo {public static void Main (string[] args) throws IOException {//Create object, it is important to understand the file being manipulated.

Assuming that the folder already has a file with the same name, the file will be overwritten. FileWriter fwriter = new FileWriter ("Demo.txt");//write in stream, not directly in Demo.txt ("I ' s Fwriter.write");//flush data in stream// Fwriter.flush (); Fwriter.close ();//The stream is closed after a buffer stream//flush refreshed before it is closed}}

2. Add an exception capture try to the write file operation:

1) FileWriter (), write (), close () will produce a throw;

2) We will put close () in the finally inside to deal with;

3) so. The fwriter variable needs to be defined outside, and once again, try Close () again.

4) Note that if the file creation fails, then fwriter=null; At this point, enter finally to call Close (). Abnormal.

Therefore, a null is required.

5) Note that a "\ r \ n" is required for line breaks.

Package Io.dol.sn;import Java.io.filewriter;import Java.io.ioexception;public class Filewriterdemo {public static void Main (string[] args) {//need to write the statement outside. Otherwise, the variable is not defined in finally FileWriter Fwriter = null;try {fwriter = new FileWriter ("Demo.txt");//Pay attention to the need to use "\ r \ n" for line breaks To implement Fwriter.write ("I'm dolphin.\r\n I call dolphins."); catch (IOException e) {System.out.println ("File creation Failed");} Finally{try {//Note: Close () try//the same time if the convection is empty to infer if (fwriter! = null) Fwriter.close ();} catch (IOException E2) { System.out.println ("File close Failed");}}}

3. Read the file FileReader

The read () function reads one character at a time. The return value is int.

Package Io.dol.sn;import Java.io.filereader;import Java.io.ioexception;public class Filereaderdemo {public static void Main (string[] args) {FileReader Freader = null;try {freader = new FileReader ("Demo.txt");//read () read one character at a time and move it backwards int ch = Freader.read ();//system.out.println (CH); System.out.println ((char) ch);} catch (IOException e) {System.out.println ("file read failed"),} finally{try {if (freader! = null) Freader.close ();} catch ( IOException E2) {System.out.println ("file close Failed");}}}
after Improvement 1, a while () loop is used to read one character at a time until all the read of the file is completed.

Package Io.dol.sn;import Java.io.filereader;import Java.io.ioexception;public class Filereaderdemo {public static void Main (string[] args) {FileReader Freader = null;try {freader = new FileReader ("Demo.txt"); int ch = 0;//read () reads one character at a time. and take the initiative to move backwards while (ch = freader.read ())! =-1) {//system.out.println (CH); System.out.print ((char) ch);}} catch (IOException e) {System.out.println ("file read failed"),} finally{try {if (freader! = null) Freader.close ();} catch ( IOException E2) {System.out.println ("file close Failed");}}}

After 2 improvements, each time a piece of data is read until the file is read out.

Take a look here. int read (char []) returns the data to which the value was successfully read.

Package Io.dol.sn;import Java.io.filereader;import Java.io.ioexception;public class Filereaderdemo {public static void Main (string[] args) {FileReader Freader = null;try {freader = new FileReader ("Demo.txt");//Note that there is a casual opening of 3 spaces, generally opening up to 2 integer times. such as 1024char buf[] = new Char[3];int n = 0;//int read (char[]) The return value is the number of read successes while ((N=freader.read (BUF))! =-1) {System.out.print (New String (Buf,0,n));}} catch (IOException e) {System.out.println ("file read failed"),} finally{try {if (freader! = null) Freader.close ();} catch ( IOException E2) {System.out.println ("file close Failed");}}}
4, file buffer write file operation BufferedWriter

1) The occurrence of buffer is to improve the operation efficiency of the flow;

2) So, before creating the buffer, there must be a stream;

3) Buffers provide a cross-platform approach: NewLine () does not make too much of a description here.

Package Io.dol.sn;import java.io.bufferedwriter;import java.io.filewriter;import java.io.ioexception;//buffer appears. is to improve the operational efficiency of the flow;//So. Before the buffer is created. There must be a stream. public class Bufferwriterdemo {public static void main (string[] args) {BufferedWriter bfbufferedwriter = null; FileWriter Fwriter = null;try {//Creates a file Fwriter = new FileWriter ("Demo.txt");//associates the data stream with a buffer, which is then directly to the buffer operation Bfbufferedwriter = new BufferedWriter (fwriter); Bfbufferedwriter.write ("I ' M dolphin.\r\n I call Dolphin."); catch (IOException e) {System.out.println ("File creation Failed");} Finally{try {if (bfbufferedwriter! = null) {//All involved buffers need to flush data bfbufferedwriter.flush ();//This closes the buffer. In fact, it is equivalent to shutting down the data stream bfbufferedwriter.close ();//fwriter.close () does not need to call the}} catch (IOException E2) {System.out.println (" File close failed ");}}}

5, the file buffer read file operation BufferedReader

Note: the ReadLine () method here only returns the content before the carriage return. Does not return carriage returns, so the time to read multiple lines. There will be no line breaks.

Package Io.dol.sn;import Java.io.bufferedreader;import Java.io.filereader;import Java.io.ioexception;public class Bufferreaderdemo {public static void main (string[] args) {BufferedReader bfbufferedreader = null; FileReader Freader = null;try {//Open a file Freader = new FileReader ("Demo.txt");//associate the data stream with a buffer, which is then directly to the buffer operation Bfbufferedreader = new BufferedReader (freader);//string ReadLine () This method is very cow. Reads one row of data from text at a time string buf = Bfbufferedreader.readline (); System.out.println (BUF);} catch (IOException e) {System.out.println ("File creation Failed");} Finally{try {if (bfbufferedreader! = null) {Bfbufferedreader.close ();}} catch (IOException E2) {System.out.println (" File close failed ");}}}
after the improvement, read one line at a time, loop read, implement read all the data in the file.

Package Io.dol.sn;import Java.io.bufferedreader;import Java.io.filereader;import Java.io.ioexception;public class Bufferreaderdemo {public static void main (string[] args) {BufferedReader bfbufferedreader = null; FileReader Freader = null;try {freader = new FileReader ("Demo.txt"); bfbufferedreader = new BufferedReader (freader);// String ReadLine () read to the end of the file returns a value of nullstring buf = Null;while ((Buf=bfbufferedreader.readline ())! = null) System.out.println (BUF);} catch (IOException e) {System.out.println ("File creation Failed");} Finally{try {if (bfbufferedreader! = null) {Bfbufferedreader.close ();}} catch (IOException E2) {System.out.println (" File close failed ");}}}
6, tracking line number buffer character input stream LineNumberReader

This class defines methods Getlinenumber (int) and getlinenumber () for setting line numbers and getting line numbers;

Package Io.dol.sn;import Java.io.filereader;import Java.io.ioexception;import Java.io.linenumberreader;public class Linenumberreaderdemo {public static void main (string[] args) {LineNumberReader lnreader = null; FileReader Freader = null;try {freader = new FileReader ("Demo.txt"); lnreader = new LineNumberReader (Freader); The String buf = null;//line number is started from 0 by default. We set the Lnreader.setlinenumber from 100, while ((Buf=lnreader.readline ()) = null) System.out.println ( Lnreader.getlinenumber () + ":" +buf);} catch (IOException e) {System.out.println ("File creation Failed");} Finally{try {if (lnreader! = null) {Lnreader.close ();}} catch (IOException E2) {System.out.println ("file close Failed");}}}

7. Write file FileOutputStream of Byte stream operation

When we need to manipulate the image video and other data, we need to use a byte stream.

Package Io.dol.sn;import Java.io.fileoutputstream;import java.io.ioexception;//image data is required to use the byte stream public class Fileoutputstreamdemo {public static void main (string[] args) {FileOutputStream fos = null;try {fos = new FileOutputStream ( "Demo.txt");//Direct operation of the byte stream is not required to refresh the Fos.write ("ABCDE". GetBytes ());} catch (IOException e) {System.out.println ("File creation Failed");} Finally{try {if (fos! = null) {Fos.close ();}} catch (IOException E2) {System.out.println ("file close Failed");}}}
8. Read file FileInputStream of Byte stream operation

It is recommended to use this method to read the data, the method I talked about later is not recommended;

Package Io.dol.sn;import Java.io.fileinputstream;import Java.io.ioexception;public class Fileinputstreamdemo {public static void Main (string[] args) {FileInputStream fis = null;try {fis = new FileInputStream ("Demo.txt"); byte[] buf = new by Te[1024];int len = 0;while ((Len=fis.read (BUF))! =-1) {System.out.println (new String (Buf,0,len));}} catch (IOException e) {System.out.println ("File creation Failed");} finally{try {if (FIS! = null) {Fis.close ();}} catch (IOException E2) {System.out.println ("file close Failed");}}}
to add an additional method, it is not recommended to use this method to read data.

Package Io.dol.sn;import Java.io.fileinputstream;import Java.io.ioexception;public class Fileinputstreamdemo {public static void Main (string[] args) {FileInputStream fis = null;try {fis = new FileInputStream ("Demo.txt");//get file size int num = f Is.available ();//define a just-fine array size. So there is no need for the For loop to read. But how about this, a movie 1G size, do we open up a so large array?! byte[] buf = new Byte[num];int len = 0;while ((Len=fis.read (BUF))! =-1) {System.out.println (new String (Buf,0,len));}} catch (IOException e) {System.out.println ("File creation Failed");} finally{try {if (FIS! = null) {Fis.close ();}} catch (IOException E2) {System.out.println ("file close Failed");}}}
9, the use of byte stream to achieve the copy operation of the file Bufferinputstream, Bufferoutputstream

1) Creation of two streams (input stream, output stream);

2) associated with the buffer, (this step can be omitted only to speed up the copy).

3) Start copy.

A sample MP3 copy is shown below:

Package Io.dol.sn;import Java.io.bufferedinputstream;import Java.io.bufferedoutputstream;import Java.io.fileinputstream;import Java.io.fileoutputstream;import java.io.ioexception;//Join buffer to operate the byte stream, Copy 1.mp3 to 2.mp3public class Bufferioputstreamdemo {public static void main (string[] args) {Bufferedinputstream BFI =  Null Bufferedoutputstream BFO = null; try {//two byte stream is associated with buffer stream BFI = new Bufferedinputstream (New FileInputStream ("D:\\1.mp3")); BFO = new Bufferedoutputstream ( New FileOutputStream ("D:\\2.mp3")); int bytenum = 0;//the hard drive data into the buffer first, the read () method is to fetch the data from the buffer while ((Bytenum=bfi.read ())! =-1) { Bfo.write (Bytenum);}} catch (IOException e) {System.out.println ("File creation Failed");} Finally{try {if (BFI! = null) bfi.close (); if (BFO! = null) Bfo.close ();} catch (IOException E2) {System.out.println ("file close failed ");}}}}
Original address: http://blog.csdn.net/qingdujun/article/details/41154807

References: Java video, Bi Xiangdong.



Summary of Java I/O operations

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.