"JAVA" io detailed

Source: Internet
Author: User
Tags readline string splitter

This article is derived from a combination of various web texts

Reference

[1]http://blog.csdn.net/yczz/article/details/38761237

[2]http://www.cnblogs.com/pepcod/archive/2013/01/20/2913435.html

[3]http://blog.csdn.net/zhangerqing/article/details/8466532

First, hang a diagram, which is a hierarchy of classes in Java referenced from [1].

Java IO is stream-based.

What the stream is:

Stream equivalent to a continuous uninterrupted information, the middle without some separators, information from the source to the end of the destination does not change, pass what to get what

For example, TCP is the flow-oriented, that is, from the client to the server side, the transmission is what is not to the first second send between the addition of some separators.

UDP is message-oriented, that is, the first pass will be preceded by a header, to distinguish between each transmission of information.

As an example:

The flow is to transmit Hello world.

The non-streaming is the transmission of Hello World, which may be received by $hello $world words with information for segmentation.

You can imagine

Flow-oriented equivalent to a water pipe from your home to a water company, and the water company gave you what you got at home.

and the message-oriented (non-streaming) equivalent to the water supply company to your home, a bucket of a bucket of delivery. What you get is probably not just water, but buckets.

Input stream and output stream:

The direction of the flow is divided into input and output

The computer stores memory and external memory, which is memory and hard disk

A hard drive can be seen as a warehouse, and memory is the factory. You have to work in the factory, you get the raw material from the warehouse to the factory.

That is, from the hard disk to send files into memory, which is called input. For your program, this is the input. Because the key location in the memory

And the data you're working on is going to be stored in the warehouse, which is the output, that is, from memory to the hard disk.

Since then, the flow has been divided into two types depending on the direction

Input stream from hard drive input to memory input

Output stream from memory to memory output

Byte stream and character stream:

Depending on the basic unit of information in the stream, the stream is divided into byte stream and character stream, that is, the byte stream consists of a single character, and the character stream consists of a char, each character in Java consists of two bytes Unicode16

In the hard disk, all files are stored in bytes, including text files, but in practice, many files are text files, there is a character stream generation,

Literally, the stream of characters is appropriate for the input and output operation of a character file, which is a text file. Because it is handled in the character unit.

The byte stream is suitable for files that do not contain characters, such as audio and video images.

Javaio objects to manipulate:

byte array, String, file, pipeline, stream, network resource

Each object has a corresponding class that is used to manipulate them.

Base class for Javaio:

Four classes are divided into Java based on the output and input of byte stream and character stream

Stream of Byte stream characters

Input InputStream Reader

Output OutputStream Writer

File class:

File is literally files, in Linux and other system files are divided into two, one is a normal file, a directory file

File is mainly for disk operations, such as the creation of files, folder creation and so on.

1. Construct the file f=new file ("C:/1.txt"); File represents something represented by a path.

2. If it is a directory then you can call the list method F.list () to get the file name in the directory return is string[]

3. There are many other features that can be viewed in the API

InputStream:

Abstract class, the base class for all input byte streams, the main operation is read ()

Sub-classes of the corresponding various objects:

Bytearrayinputstream: A class that handles byte arrays, allowing memory buffers to be used as inputstream.

StringBufferInputStream: Convert string to InputStream, internal implementation is stringbuffer.

FileInputStream: Reads data from the file.

PipedInputStream: Used to read data from the pipeline.

Sequenceinputstream: Converts multiple Stream objects into a single inputstream.

FilterInputStream: Adorner class that provides functionality for other InputStream classes.

Reader

Abstract class, the base class for all input character streams as long as it is read ()

Sub-classes for various objects:

Refer to the Javaio classic example in [3]: The use of BufferedReader:

1. Buffer input file with BufferedReader

    

1  Public StaticString read (string filename)throwsException {2 3BufferedReader br =NewBufferedReader (Newfilereader (filename)); 4 5 String S; 6 7StringBuffer SB =NewStringBuffer (); while((s = br.readline ())! =NULL) {  8 9Sb.append (s + "\ n")); Ten  One } A  - Br.close ();  -  the         returnsb.tostring ();  -  -}

BufferedReader is a wrapper class that is used to package an ordinary reader. Better use and performance for common reader

Generally use a reader or writer or inputstream or outputstream as if the buffered inside to improve performance operations

Use of StringReader:

The data source is a string object,

Equivalent to read in from memory.

You can also read by line, and so on.

1 ImportJava.io.*;2  Public classSrdemo3 {4    Public Static voidMain (String args[])throwsIOException5   {6String S1 = "for outsiders\nthe software engineer\nlooks housed\nin a golden cage";7StringReader Sreader =NewStringReader (S1);8BufferedReader Breader =NewBufferedReader (sreader);9         Ten String S2; One      while((S2 = Breader.readline ())! =NULL) A     { - System.out.println (S2); -     } the Breader.close (); Sreader.close (); -   } -}

Reference [3]: Writing a standard file read-write class

  

ImportJava.io.BufferedReader;ImportJava.io.File;ImportJava.io.FileReader;Importjava.io.IOException;ImportJava.io.PrintWriter;Importjava.util.ArrayList;Importjava.util.Arrays;/*** A very useful file operation class. 2012-12-19 * *@authorBruce Eckel, edited by erqing **/ Public classTextfileextendsArraylist<string> {    Private Static Final LongSerialversionuid = -1942855619975438512l; //Read a file as a String     Public Staticstring Read (string filename) {StringBuilder sb=NewStringBuilder (); Try{BufferedReader in=NewBufferedReader (NewFileReader (NewFile (filename). Getabsolutefile ());            String s; Try {                 while((s = in.readline ())! =NULL) {sb.append (s); Sb.append ("\ n"); }            } finally{in.close (); }        } Catch(IOException e) {Throw NewRuntimeException (e); }        returnsb.tostring (); }    //Write A single file on one method call     Public Static voidWrite (string fileName, string text) {Try{PrintWriter out=NewPrintWriter (NewFile (fileName). Getabsolutefile ()); Try{out.print (text); } finally{out.close (); }        } Catch(IOException e) {Throw NewRuntimeException (e); }    }    //Read a file,spilt by any regular expression     Publictextfile (String fileName, String splitter) {Super(Arrays.aslist (Read (FileName). Split (splitter))); if(Get (0). Equals ("") Remove (0); }    //normally read by lines     Publictextfile (String fileName) { This(FileName, "\ n"); }     Public voidWrite (String fileName) {Try{PrintWriter out=NewPrintWriter (NewFile (fileName). Getabsolutefile ()); Try {                 for(String item: This) out.println (item); } finally{out.close (); }        } Catch(IOException e) {Throw NewRuntimeException (e); }    }    //Test,i generated a file named Data.d at the root     Public Static voidMain (string[] args) {/*read () test*/System.out.println (Read ("DATA.D"));//testing is ok!        /*write () test*/Write ("Out.d", "Helloworld\negg");//testing is ok!        /*constractor Test*/textfile TF=NewTextfile ("DATA.D");//testing is ok!    }}

Standard binary file Operation class
ImportJava.io.BufferedInputStream;ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.IOException;/*** To read the binary file * *@authorerqing **/ Public classBinaryfile {/*The Parametre is a file*/     Public Static byte[] Read (file file)throwsIOException {bufferedinputstream bf=NewBufferedinputstream (Newfileinputstream (file)); Try {            byte[] data =New byte[Bf.available ()];            Bf.read (data); returndata; } finally{bf.close (); }    }    /*The param is the path of a file*/     Public Static byte[] Read (String file)throwsIOException {returnReadNewfile (file). Getabsolutefile ()); }}

"JAVA" io detailed

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.