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. 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 () automatically calls flush () to flush the stream before closing the stream. When off, 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 explicitly manipulate the file. If a file with the same name already exists in the directory, 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 will be closed after a buffer stream//flush refreshed before it is closed}}

2. Add exception capture try to write file operation:

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

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

3) Then, you need to define the Fwriter variable outside, and you need to try again close ().

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

5) Note that the line break needs to be implemented with "\ r \ n".

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 declaration outside, otherwise the variable is undefined in finally FileWriter Fwriter = null;try {fwriter = new FileWriter ("Demo.txt") ;//Note that the line break requires "\ r \ n" to implement Fwriter.write ("I'm dolphin.\r\n I call Dolphin.");} catch (IOException e) {System.out.println ("File creation Failed");} Finally{try {//Note: Close () is try//to determine if the convection is empty at the same time 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, and 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 () reads one character at a time and automatically moves backwards int ch = f Reader.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 files have been 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"); int ch = 0;//read () reads one character at a time and automatically moves backwards (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. Note here that int read (char []) returns the value of the data that 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 of the 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;//Therefore, there must be a stream before the buffer is created. 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 refresh the data Bfbufferedwriter.flush ();//Here the buffer is closed, 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 contents before the carriage return, and does not return the carriage returns, so there is no line break when reading multiple lines.

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 bull, reading 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); String buf = null;//line number default is starting from 0, we set starting from 100 lnreader.setlinenumber (+); 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 the byte stream;

Package Io.dol.sn;import Java.io.fileoutputstream;import java.io.ioexception;//picture 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 that the following does not have to be read for the loop;//But how about this, a movie 1G size, do we open up such a 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 copying.

A MP3 Copy example 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;//Add buffer to manipulate 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 presenter.

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.