Java Learning Note Six (I/O stream)

Source: Internet
Author: User

1. Introduction

In the actual development process will often use the data input/output operations, this blog focus on the analysis, Java frequently used in the IO operation of the class. In Java, you can divide a common stream into two parts: a byte stream and a character stream.



1. Abstract base class for streams


BYTE stream Character Stream
Input stream InputStream Reader
Output stream OutputStream Writer

As the table shows, both character and byte streams have their own base classes, and the rest are operations that inherit the extended stream of the base class. The following will focus on the explanation. (as long as a character stream, the byte stream is the same as its operation, except that the file type of the operation is inconsistent)



2. Character Stream

Specifically for reading and writing text data, which can be opened with Notepad, such as TXT, Java, HTML data stream of the operation of the range

1. Character output stream--filewriter

The character output stream typically applies filewriter, and then calls its constructor, passing the string's file name and writing the character in the file. The second call to the parent class method write (String str) writes a string, where it is important to note that the character stream write data, not directly written in the destination file, but written in memory, must walk a method, refresh, the memory of the data flushed to the destination file, character stream write data must be refreshed. The void Flush () method is generally called, and the stream object needs to be closed after the end of the run.

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" ><span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >package com. Io;import Java.io.filewriter;import Java.io.ioexception;public class FileWriterDemo1 {public static void main (string[] args) {FileWriter FW = Null;try {//In this form, the previous data information is overwritten each time//fw=new FileWriter ("C:\\exception.txt");//With this constructor, Data will be added in append form. Query native default encoding means Gbkfw=new FileWriter ("C:\\exception.txt", True), Fw.write ("Abd"), Fw.flush (), Fw.write ("Get H ah Oh"); Fw.flush ();} catch (IOException e) {e.printstacktrace (); throw new RuntimeException ("File write Failed");} Finally{try {//must be judged here otherwise, an error may be reported with a null pointer for exception information. if (fw!=null) {fw.close ();}} catch (IOException e) {e.printstacktrace (); throw new RuntimeException ("Close resource Failed");}}} </span></span>


FileWriter Write text file operation as follows

The form of a single character, called by the parent class of the write (int c) method

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" ><span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >package CN. Io.iostream;import java.io.*;class FileWriterDemo1 {public static void main (string[] args) {//Create output Stream object  FileWriter FW = null;try{  fw = new FileWriter ("C:\\1.txt");  Fw.write ("abc");  Fw.flush ();  Fw.write ("adb");  Flushes in-memory data to a file  Fw.flush ();} catch (IOException e) {   e.printstacktrace ();   throw new RuntimeException ("Write Data Failed");} finally{            try{  if (fw!=null)         fw.close ();} catch (IOException e) {   e.printstacktrace ();   throw new RuntimeException ("Close Stream object Failed");}}} </span></span>


In the form of a character array, the method called is as follows

~write (char[] ch) passing the entire character array

~write (char[] ch,int off,int Len) writes part of the array, off begins subscript, Len number

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" ><span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >package CN. io.iostream;/* * FileWriter writes the file as an array *  */import java.io.*;p ublic class FileWriterDemo2 {public static void main ( String[] args) throws IOException {//calls this output stream's constructor and will be appended to the file contents FileWriter fw = new FileWriter ("C:\\demo.txt", true); Fw.write (char[] ch= {' A ', ' B ', ' C '};fw.write (ch,1,1); Fw.write ("Sefser"); Fw.flush (); Fw.close ();}} </span></span>

Note that if you want to append the write to the file instead of overwriting the original content, simply call it FileWriter(String fileName, boolean append)构造方法即可 when you create the input stream object


2.字符输入流

字符输入流一般应用的是FileReader读取文本文件,然后调用其构造方法,创建输入流对象,传递字符文件名,例如new FileReader(‘文件名‘),读取一个字符 int read()方法,每次只读取一个字符,然后指定的read()方法,会自动的向后读取一个,读到末尾的时候,将会返回-1

读取单个字符

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" ><span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >package CN. io.iostream;/* * Use character input stream object to read file operation */import java.io.*;p Ublic class Filereaderdemo {public static void main (string[] args ) throws ioexception{//create an input stream object FileReader fr = new FileReader ("C:\\demo.txt");//Call the Read method to read only one character at a time int x = 0;while ((x = f R.read ())!=-1) {System.out.print ((char) x);} Fr.close ();}} </span></span>

reading character array operations

int read(char[] cbuf):读取方法,传递字符数组,返回值int代表有效读取的字符个数,此方法读取效率高

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" ><span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >package cn.itcast.iostream;/* * Reads a character array using a character input stream object */import java.io.*;p ublic class FileReaderDemo1 {public static void Main (string[] args) throws Ioexception{filereader fr = new FileReader ("C:\\demo.txt");//create an array of characters char[] ch = new char[ 1024];//is generally a multiple of 1024 int x = 0; while ((X  = Fr.read (ch))!=-1) {//string (char[] value, int offset, int count) SYSTEM.OUT.PR Int (new String (ch,0,x));} Fr.close ();}} </span></span>


Copy file operation

Use the input and output streams of a character stream to manipulate the file's copy function

The first way, read a character, write a character

<span style= "font-family:simsun;font-size:18px;" ><span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >package CN. io.iostream;/* * Use character stream to implement copy function */import java.io.*;p ublic class CopyText {public static void main (string[] args) {Long star t = System.currenttimemillis ();//The object that creates the character input and output stream FileReader FR = null; FileWriter FW = null;try{//calls its constructors respectively FR = new FileReader ("C:\\demo.txt"), FW = new FileWriter ("D:\\demo.txt");// Define variables to error The value of a single character read int len = 0; while (len = Fr.read ())!=-1) {fw.write (len); Fw.flush ();} catch (IOException e) {throw new RuntimeException ("Copy Failed");} Finally{try{if (Fw!=null) Fw.close ();} catch (IOException e) {throw new RuntimeException ("Shutdown write stream failed");} Finally{try{if (Fr!=null) Fr.close ();} catch (IOException e) {throw new RuntimeException ("failed to close input stream");}}} Long end = System.currenttimemillis (); System.out.println (End-start);}} </span></span> 

Second method: read a character array, write a character array

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" ><span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >package CN.  io.iostream;/* * Use input and output streams to complete the copy operation */import java.io.*;p Ublic class CopyText2 {public static void main (string[] args) {long Start = System.currenttimemillis ();//create character input and output stream object FileReader fr = null respectively; FileWriter FW = null;try{//calls its constructor to instantiate FR = new FileReader ("c:\\e.html"), FW = new FileWriter ("d:\\1.html");// Defines the character array to read char[] ch = new Char[1024];int len = 0; while (len = Fr.read (ch))!=-1) {fw.write (Ch,0,len); Fw.flush ();}} catch (IOException e) {throw new RuntimeException ("Copy Failed");} Finally{try{if (Fw!=null) Fw.close ();} catch (IOException e) {throw new RuntimeException ("failed to close output stream");} Finally{try{if (Fr!=null) Fr.close ();} catch (IOException e) {throw new RuntimeException ("failed to close input stream");}}} Long end = System.currenttimemillis (); System.out.println (End-start);}} </span></span>


Note: Using the form of a read character array can be much faster


3. Buffer Stream

When reading or writing, you can also buffer the characters or bytes in the form of buffer streams, thus enabling efficient reading and writing of characters, arrays, and rows.


Character Bytes
Buffered input stream BufferedReader Bufferedinputstream
Buffered output stream BufferedWriter Bufferedoutputstream

The main is in the buffer stream can take a read line to manipulate the source file.

All operations are consistent, all in the form of construction methods, passing characters or byte streams, such as BufferedReader (Reader R), to pass in FileReader, through the string ReadLine () method to read a line of the file, When the end of the file is read, a null value is returned

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >package com. Io;import Java.io.bufferedreader;import Java.io.filenotfoundexception;import Java.io.filereader;import java.io.ioexception;/* * Character input stream, BufferedReader, reads a line of text function */public class Bufferedreaderdemo {public static void main ( String[] args) throws IOException {//build character input stream buffer object, pass character input object BufferedReader bfr=new BufferedReader ("FileReader 1.txt "));//start reading a line of text, return stringstring line=bfr.readline (); System.out.println (line);}} </span>


the rest of the Bufferedinputstream, Bufferedoutputstream, BufferedReader, bufferedwriter the use of the same, refer to the above notation.

The effect of file copying is realized by using buffer stream.


<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >package com. Io;import java.io.bufferedreader;import java.io.bufferedwriter;import Java.io.filereader;import java.io.FileWriter Import Java.io.ioexception;import javax.management.runtimeerrorexception;/* * Use character stream buffers to assign values * Read and write lines, write newline */public class CopyTest2 {public static void main (string[] args) {/////Anonymous object form, create stream object and Cache de object BufferedReader bfr = null; BufferedWriter BRW = null;try {bfr = new BufferedReader (New FileReader ("C:\\1.txt")); BRW = new BufferedWriter (New Filewrit ER ("c:\\2.txt"));//read a line, write a line, write a newline string line = Null;while ((line = Bfr.readline ())! = null) {Brw.write (line);//The ability to break lines BRW . NewLine (); Brw.flush ();}} catch (Exception e) {e.printstacktrace (); throw new RuntimeException ("Copy Failed");} Finally{try {if (bfr!=null) {Bfr.close ()}} catch (IOException E2) {throw new RuntimeException ("Write shutdown Failed");} Finally{try {if (brw!=null) {Brw.close ()}} catch (IOException E3) {throw new RuntimeException ("read in close Failed");}}}} </span>



4. Conversion Flow

The conversion stream in Java generally has two respectively, OutputStreamWriter, InputStreamReader, is the character flow to the word stream of the bridge.


正如所示,通过缓冲流就可以把字节流转换成为字符流来处理,通过缓冲区一包装,就可以读取行的操作了。

<span style= "font-family:simsun;font-size:18px;" >package com. Io;import Java.io.bufferedreader;import Java.io.bufferedwriter;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.io.outputstreamwriter;public class TranseDemo3 {public static void main (string[ ] args) throws IOException {/*//console input byte stream inputstream in=new fileinputstream ("C:\\1.java");//Create a transform stream object, Pass byte input stream inputstreamreader isr=new inputstreamreader (in);//Since you have converted in to a character stream ISR, you can use the character stream buffer object BufferedReader. Line Read BufferedReader bfr=new BufferedReader (ISR); OutputStream Out=system.out;outputstreamwriter osw=new OutputStreamWriter (out); BufferedWriter bfw=new BufferedWriter (OSW); */bufferedreader bfr=new BufferedReader (New InputStreamReader (System.in) ); BufferedWriter brw=new BufferedWriter (New OutputStreamWriter (System.out)); String Line=null;while ((Line=bfr.readline ())!=null) {brw.write (line); Brw.flush (); Brw.newline ();} Brw.close (); Bfr.close ();}} </span> 










Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java Learning Note Six (I/O stream)

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.