JAVA IO API Usage detailed _java

Source: Internet
Author: User
Tags alphabetic character file copy flush readline

I. Theoretical preparation
Flow is an abstract concept, is the abstraction of the input, Java program, the data input/output operations are "flow" mode, the device can be file, network, memory and so on. The flow has directionality, as to whether it is an input stream or an output stream is a relative concept, generally with the program (small Marco is the machine) for reference, if the flow of data to the program to the device, we become the output stream, and vice versa we called the input stream, you can think of the stream as a "flow pipe" (a lot of information is said), Naturally there is the concept of direction.
The stream hides the specific operations inside the I/O device. All InputStream and reader derived classes have a basic, inherited, read () method that reads a single or byte array.
Java is divided into bytes (stream end) and character stream (Reader, write end), and then into input streams (inputstream, reader) and output stream (OutputStream, write), the input output relative to memory. When reading characters with character streams, such as text files, XML (I think XML is an alphabetic character, which belongs to ASCII files, why not stream read?) Wait When reading binary files, use a byte stream, such as RAR, EXE, etc. is not a document other than text (picture). The flow at the beginning of the buffered just adds a buffer to improve efficiency in reading and writing. The character stream cannot be output directly, and it needs to be converted into a byte throttling to output (this is really just known)!
There are three basic types of nodes in the Java 2 SDK: Files (file), memory (memory), pipelines (pipe).
Here's a look at the classic picture of the IO section of the Zhengli textbook.
The streams that inherit from Inputstream/outputstream are used to input/output data to the program, and the units of the data are bytes (byte=8bit), such as graphs, dark nodes, and light-colored for processing streams.

Streams that inherit from Reader/writer are used to input/output data to the program, and the units of the data are characters (2byte=16bit), such as graphs, dark-colored nodes, and light-colored for processing streams.

Two. Usage analysis
General usage principles of Java IO (part from Baidu Library):
(1) Classification by data source (whereabouts):
Is file: FileInputStream, FileOutputStream, FileReader, FileWriter
It's Byte[]:bytearrayinputstream, Bytearrayoutputstream.
Is char[]: CharArrayReader, Chararraywriter
It's String:stringbufferinputstream, StringReader, StringWriter.
Network data streams: InputStream, OutputStream, Reader, Writer
(2) According to whether or not to format the output points:
To format the output: PrintStream, PrintWriter
(3) Whether or not to buffer points:
To buffer: Bufferedinputstream, Bufferedoutputstream, BufferedReader, BufferedWriter.
(4) According to the data format:
binary format (as long as it cannot be determined to be plain text): InputStream, OutputStream, and all subclasses with stream end
Plain text Format (with pure English and Chinese characters or other encoding methods); reader, writer and all of the subclasses of reader, writer
(5) According to the input and output points:
Input: Reader, subclass of InputStream type; output: Writer, subclass of OutputStream type
(6) Special needs:
Conversion classes from stream to Reader,writer: InputStreamReader, OutputStreamWriter
Object input and output: ObjectInputStream, ObjectOutputStream
interprocess communication: Pipeinputstream, Pipeoutputstream, Pipereader, Pipewriter
Merge input: Sequenceinputstream
More special needs: Pushbackinputstream, Pushbackreader, Linenumberinputstream, LineNumberReader
(7) The general guidelines for deciding which class to use and its construction process are as follows (regardless of special needs):
Consider what the original data format is: Is it text? Is it input or output? Convert Stream required: InputStreamReader, OutputStreamWriter? What is the data source (whereabouts): file? Memory? Internet? Whether to buffer: BufferedReader (Special note: Be sure to notice whether ReadLine () is defined, what is more specific than read, write more special input or output methods) to format the output: print.

Three. Several examples
Or the winter vacation time to write, the right when the review, folding code plug-ins can not find, first look at it.
1.system.in

Copy Code code as follows:

Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
/*
* System.in is InputStream static final, contains polymorphism, called synchronous or blocking type
* Read ASCII and binary files (Pictures), while the letters are ASCII characters (personal understanding).
*/
public class Testsystemin {
public static void Main (string[] args) {
InputStreamReader ISR = new InputStreamReader (system.in);
BufferedReader br = new BufferedReader (ISR);//Have ReadLine
String s = null;
try {
s = Br.readline ();
while (S!=null) {
if (S.equalsignorecase ("Exit")) {
Break
}
System.out.println (S.touppercase ());
s = Br.readline ();
}
Br.close ();
}catch (IOException e) {
E.printstacktrace ();
}
}
}

2.buffer
Copy Code code as follows:

Import Java.io.BufferedReader;
Import Java.io.BufferedWriter;
Import Java.io.FileReader;
Import Java.io.FileWriter;
Import java.io.IOException;
public class Testbuffer {
public static void Main (string[] args) {
try {
Review the modification date to determine if the file is new
BufferedWriter bw = new BufferedWriter (New FileWriter ("D:/java.txt"));
BufferedReader br = new BufferedReader (New FileReader ("D:/java.txt"));
String s = null;
for (int i=1; i<100; i++) {
s = string.valueof (Math.random ());
Bw.write (s);
Bw.newline ()/Line Wrap
}
Flush the buffer of the stream, BR does not have the method
Bw.flush ();
while ((S=br.readline ())!=null) {
System.out.println (s);
}
Bw.close ();
Br.close ();
}catch (IOException e) {
E.printstacktrace ();
}
}
}

3.FileInputStream
Copy Code code as follows:

Import java.io.*;
public class Testfileinputstream {
public static void Main (string[] args) {
FileInputStream in = null;
try {
in = new FileInputStream ("E:/1.txt");
}catch (FileNotFoundException e) {
SYSTEM.OUT.PRINTLN ("File not Found");
System.exit (-1);
}
The following indicates that the file was found
int tag = 0;
try {
Long num = 0;
while (tag = In.read ())!=-1) {
Read is a word throttling, if the Chinese characters on the display is not normal, using reader to solve the
System.out.print ((char) tag);
num++;
}
In.close ();
System.out.println ();
System.out.println ("read" + num + "character");
}catch (IOException E1) {//read and close will throw IOException
SYSTEM.OUT.PRINTLN ("file read error");
System.exit (-1);
}
}
}

4.FileOutputStream to achieve the replication function
Copy Code code as follows:

Import java.io.*;
/*
* Implementation of the replication function
*/
public class Testfileoutputstream {
public static void Main (string[] args) {
int b = 0;
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream ("D:/java.txt");
If the following is not present, it will be automatically established.
out = new FileOutputStream ("D:/my_java.txt");
while ((B=in.read ())!=-1) {
Out.write (b);
}
In.close ();
Out.close ();
}catch (FileNotFoundException e) {
SYSTEM.OUT.PRINTLN ("The specified file cannot be found");
System.exit (-1);
}catch (IOException E1) {
System.out.println ("File copy Error");
System.exit (-1);

}
System.out.println ("file copied");
}
}

5.ObjectOutputStream and Serializable
Copy Code code as follows:

Import java.io.*;
/*
* Transient (transparent), can be used to modify the member variables,
* When serialization is not considered, modifier int, regardless of the original value of the number of
* The output is 0
*/
public class Testobjectio {
public static void Main (string[] args) throws Exception {
T t = new t ();
T.K = 8;
FileOutputStream fos = new FileOutputStream ("D:/1.txt");
ObjectOutputStream oos = new ObjectOutputStream (FOS);
Oos.writeobject (t);
Oos.flush ();
Oos.close ();

FileInputStream fis = new FileInputStream ("D:/1.txt");
ObjectInputStream ois = new ObjectInputStream (FIS);
T tread = (t) ois.readobject ();
System.out.println (tread.i + "" + TREAD.J + "" + TREAD.K);
}
}
Class T implements Serializable {
int i = 10;
int J = 9;
Double d = 2.3;
int k = 15;
}

6. Conversion encoding mode
Copy Code code as follows:

Import java.io.*;
/*
* Chinese Windows default GBK encoding method
* The appended content is displayed as a question mark and I don't know what it is.
*/
public class Testtransform {
public static void Main (string[] args) {
try {
OutputStreamWriter OSW = new OutputStreamWriter (New FileOutputStream ("D:/java.txt"));
Osw.write ("Hello 123");//You can write the string directly, including Chinese, because the character stream is outside.
SYSTEM.OUT.PRINTLN ("Encoding mode:" + osw.getencoding ());//iso8859_1 is a Western European language, also known as latin-1, at this time not considered Oriental, GB (ISO) for Unicode
Osw.close ();
OSW = new OutputStreamWriter (New FileOutputStream ("D:/java.txt", True), "Iso8859_1"),//true indicates append
Osw.write ("This is the additional content");
SYSTEM.OUT.PRINTLN ("Encoding mode:" + osw.getencoding ());
Osw.close ();
}catch (IOException e) {
E.printstacktrace ();
}
}
}
7. Output redirection
[Code]
Import java.io.*;
/*
* The print stream belongs to the output stream, and there are many ways to overload it,
* PrintWriter and PrintStream do not throw exceptions, and the user obtains information by detecting the error state.
* Contains automatic flush function, what is the use, in the JSP also want to output some things,
* But do not have to throw an exception every time.
*/
public class Testprintstream {
public static void Main (string[] args) {
PrintStream PS = null;
try {
FileOutputStream fos = new FileOutputStream ("D:/java.txt");
PS = new PrintStream (FOS);

}catch (IOException e) {
E.printstacktrace ();
}
if (ps!=null) {
System.setout (PS);//Output redirection
}
int ln = 0;
for (char c=0; c<65535; C + +) {
System.out.print (c + "");
if (ln++>100) {
System.out.println ();
ln = 0;
}
}
}
}

8.DataStream
Copy Code code as follows:

Import java.io.*;
public class Testdatastream {
public static void Main (string[] args) {
First allocate a byte array in memory, then a outputstream, plus a data stream
Bytearrayoutputstream BAOs = new Bytearrayoutputstream ();
DataOutputStream dos = new DataOutputStream (BAOs);
try {//write read
Dos.writedouble (Math.random ());
Dos.writeboolean (TRUE);
Bytearrayinputstream Bais = new Bytearrayinputstream (Baos.tobytearray ());
System.out.println (Bais.available ());//A total of several bytes available
DataInputStream dis = new DataInputStream (Bais);
Write first read (queue), the following two output can not be exchanged, or the first output of a double in a byte
System.out.println (Dis.readdouble ());
System.out.println (Dis.readboolean ());
Dos.close ();
Dis.close ();
}catch (IOException e) {
E.printstacktrace ();
}
}
}

Four. Small problem
Why Writer/reader not inherit from the stream? The characters will eventually be converted into binary. Writer/readre inherited Outputstream/inputstream, such an inheritance level is not better, why to do one alone, and stream also some subclasses can implement string reading and writing. The great God answered: Single duty. It's too far-fetched.

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.