Java I/O flow (1)--character stream Operation __java

Source: Internet
Author: User
Tags readline
I/O flow

Grouped by data into byte stream and character streams (coded table, Western ASCII, China gb2312 expansion for gbk--> Unified for Unicode
--> optimization utf-8)
Character streams are based on the byte stream, specifying what table to look for
The flow is divided into input and output streams.

Common base class: byte stream InputStream outputstream
Character Streams Reader Writer

Character streams, more intuitive

1, the most common manifestation of data is file
Requirements: Create some files on the hard disk, write some data (OutputStreamWriter subclass FileWriter)
Import java.io.*;
Main () throws IOException
{
FileWriter fw=new FileWriter ("Demo.txt");
Fw.write ("ABCDE"), there is no method in the subclass, see the parent class writer method, subclass can use
Fw.flush ();
Fw.write ("haha");
Fw.flush ();

Fw.close ()//is refreshed before closing, no more flush () method is called

Fw.write ("hehe");/closed, then write can not write.

Professional handling of I/O exceptions
Import java.io.*;
Main ()
{
FileWriter Fw=null;  try{fw=new FileWriter ("Demo.txt"); Fw.write ("ABCDE");} catch (IOException e) {System.out.println (e.tostring ()); }

finally{

try{

if (fw!=null) fw.close ();

catch (IOException e) {System.out.println (e.tostring ()); } } }
The continuation of the file, starting from its constructor
FileWriter fw=new FileWriter ("Demo.txt", true);
Fw.write ("ABCDE");

2, read the text file FileReader
(1) Read a single character at a time
Main ()
{
FileReader fr=new FileReader ("Demo.txt"); int Ch=fr.read (); System.out.println ("ch=" + (char) ch);//read one character
while (true)/read a character to read the file {int ch=fr.read (); if (ch==-1) break; System.out.println ("ch=" + (char) ch);

}

Fr.close ();

}
A little better.
while ((Ch=fr.read ())!=-1)
{
System.out,println ((char) ch); (2) Read the file after reading the length of an array each time
Char[] Buf=new char[3];
int Num=fr.read (BUF);
System.out.println ("num=" +num+ "--" +new String (BUF)); An attempt was made to read the buf.length character in buf, returning the number of characters that were actually successfully read, and returning 1 at the end of the file.

Using its return value to optimize char[] buf=new char[3]; int num=0; while ((Ch=fr.read (BUF))!=-1) {System.out.println (new String (Buf,0,num));// string(char[] value, int offset, int count)
Assigns a new String that contains a character from a substring of the character array argument. }
Exercise 1: Read the file and print it on the console
Exercise 2: Copy the files in C to disk D


2, character stream buffer, improve efficiency, and do not use a character to read a character, you can read one line at a time. But need to refresh flush ()

BufferedWriter BufferedReader (1) write
Import java.io.*;
Main () throws IOException
{
FileWriter fw=new FileWriter ("Demo.txt");

BufferedWriter bufw=new BufferedWriter (FW);


Bufw.write ("ABCDE");

Bufw.newline ()//newline, replace \ r \ n, various operating system general


Bufw.flush ();

Bufw.close (); Fw.close ();
} (2) Read
Main () throws IOException
{
FileReader fr=new FileReader ("Demo.txt");

BufferedReader bufr=new BufferedReader (FR); String S1=bufr.readline ();
System.out.println (S1);
Bufr.close ();
Fr.close ();

Improve, read the line all the time and know that all the files have been read.
String Line=null;
while ((Line=bufr.readline ())!=null)
{System.out.println (line);
}

Exercise: Copy Java files through buffers


Thought explanation: The principle of the ReadLine () method \ r \ n
Mybufferedreader: Do it yourself, based on the FileReader read () method, to pass the enhanced object to the enhanced object
Class Mybufferedreader
{
Private FileReader R;
Mybufferedreader (FileReader R)
{
This.r=r;
}
Public String Myreadline ()
{StringBuilder sb=new StringBuilder ();
int ch=0;
while ((Ch=r.read ())!=-1)
{
if (ch== ' \ R ') continue;
if (ch== ' \ n ') return sb.tostring (); Else Sb.append ((char) ch);
return null; } public void Myclose ()
{R.close ();} Main ()
{FileReader fr=new filereader ("Demo.txt"); Mybufferedreader mbufr=new Mybufferedreader (FR); String Line=null; while ((Line=mbufr.myreadline ())!=null) {System.out.println (line);} mbufr.close ();
The example above is the decorative design pattern: When you want an existing object to be enhanced, you define an existing object for a class to pass in, based on existing functionality, and provide enhanced functionality, then the custom class is called a decorative class.


3, the difference between decoration and inheritance
myreader
|--mytextreader
|--mybuffertextreader
|--mymediareader
|--mybuffermediareader
|--mydatareader
|--mybufferdatareader
Trouble up there.
Class Mybufferreader
{
Mybufferreader (Mytextreader e) {}
Mybufferreader (Mymediareader e) {}
~
This is still not good, scalability, each time to modify the code, find the common type of its parameters, through the form of polymorphism, can improve its extensibility
myreader
|--mytextreader
|--mymediareader
|--mydatareader
|--mybufferreader
Class Mybufferreader extends Myreader
{
Private myreader r;//You have my combination structure.
Mybufferreader (myreader R)
{}
The decorative pattern is more flexible than inheritance, avoids the bloated inheritance system, and reduces the relationship between subclass and subclass.
4, BufferedReader subclass LineNumberReader This is also a decorative class
Getlinenumber ()

Setlinenumber ()

ReadLine ()


Main () throws Exception
{
FileReader fr=new FileReader ("Demo.txt"); LineNumberReader lnr=new LineNumberReader (FR); String Line=null; Lnr.setlinenumber (100);
while ((Line=lnr.myreadline ())!=null) {System.out.println (Lnr.getlinenumber () + ":" +line);}
Lnr.close (); Simulates a buffer object with line numbers Mylinenumberreader
Class Mylinenumberreader
{
Private Reader R;
Mylinenumberreader (Reader R)
{
This.r=r;
}
private int linenumber;
public void Setlinenumber (int linenumber)
{
This.linenumber=linenumber;
}
public void Getlinenumber ()
{
return linenumber;
}

Public String Myreadline () throws IOException
{linenumber++;

StringBuilder sb=new StringBuilder ();
int ch=0;
while ((Ch=r.read ())!=-1)
{
if (ch== ' \ R ') continue;
if (ch== ' \ n ') return sb.tostring ();
Else Sb.append ((char) ch);
}
if (Sb.length ()!=0)
return sb.tostring ();
return null;
}
public void Myclose ()
{R.close ();}
}
Main ()
{
FileReader fr=new FileReader ("Demo.txt");
Mylinenumberreader mylnr=new Mylinenumberreader (FR);

String Line=null;
while ((Line=mylnr.myreadline ())!=null)
{System.out.println (Mylnr.getlinenumber () + ":" +line);
}

Mylnr.close ();
}
Code Optimization: (Let class inherit from BufferedReader)
Class Mylinenumberreader Extend BufferedReader
{
Mylinenumberreader (Reader R)
{
Super (R);
}
private int linenumber;
public void Setlinenumber (int linenumber)
{
This.linenumber=linenumber;
}
public void Getlinenumber ()
{
return linenumber;
}

Public String Myreadline () throws IOException
{linenumber++;

/*
StringBuilder sb=new StringBuilder ();
int ch=0;
while ((Ch=r.read ())!=-1)
{
if (ch== ' \ R ') continue;
if (ch== ' \ n ') return sb.tostring ();
Else Sb.append ((char) ch);
}
if (Sb.length ()!=0)
return sb.tostring ();
return null;
*/

return Super.myreadline ();
}
public void Myclose ()
{R.close ();}
}
Main ()
{
FileReader fr=new FileReader ("Demo.txt");
Mylinenumberreader mylnr=new Mylinenumberreader (FR);

String Line=null;
while ((Line=mylnr.myreadline ())!=null)
{System.out.println (Mylnr.getlinenumber () + ":" +line);
}

Mylnr.close ();
}


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.