Summary of various Java I/O operations

Source: Internet
Author: User

From: http://www.cnblogs.com/wjun530/archive/2007/06/14/782898.html

1. Input and output1. stream represent any data source capable of producing data or any receiving source capable of receiving data. In Java I/O, all streams (including input and out streams) have two types: 1.1 byte-oriented stream, reads or writes information from or to the stream in bytes. Byte-oriented stream includes the following types: 1) input stream: 1) bytearrayinputstream: Use a buffer in the memory as inputstream 2) stringbufferinputstream: Use a String object as inputstream3) fileinputstream: Use a file as an inputstream to read files. 4) pipedinputstream: implements the pipe concept. It is mainly used in the process. 5) sequenceinputstream: merge multiple inputstreams into one inputstream2) Out stream1) bytearrayoutputstream: store information into a buffer in the memory. 2) fileoutputstream: store information into a file. 3) pipedoutputstream: the pipe concept is implemented, mainly used in the thread 4) Sequenceoutputstream: combines multiple outstreams into an outstream1.2 Unicode-oriented stream with Unicode characters, read from or write information to a stream in units of Unicode characters. Unicode-oriented stream includes the following types: 1) Input stream1) chararrayreader: corresponds to bytearrayinputstream 2) stringreader: corresponds to stringbufferinputstream 3) filereader: corresponds to fileinputstream 4) pipedreader: 2) Out stream1) chararraywrite: corresponds to bytearrayoutputstream 2) stringwrite: No bytes-oriented stream3) filewrite: corresponds to fileoutputstream 4) pipedwrite: the character-oriented stream corresponding to pipedoutputstream basically corresponds to the byte-oriented stream. The functions of the two corresponding classes are the same, and the words are different in operation. For example, chararrayreader and bytearrayinputstream both use a buffer in the memory as inputstream. The difference is that the former reads a byte of information from the memory each time, the latter reads one character from the memory each time. 1.3 conversion between two non-existing stream types: inputstreamreader and outputstreamreader: converts a byte-oriented stream into a character-oriented stream. 2. The function of "adding attributes for stream" in "stream" 2.1 "applies the Java I/O operation API described above, so that we can complete any operation we want to complete. However, through the sub-classes of filterinputstream and filteroutstream, we can add attributes for stream. The following is an example to illustrate the role of this function. If we want to write data to a file, we can perform the following operations: fileoutstream FS = new fileoutstream(test.txt”);then we can use the FS object to call write() to write data to the test.txt file. However, if we want to implement the "First cache the data to be written into the file into the memory, then write the data in the cache into the file" function, none of the above APIs can meet our needs. However, we can use the sub-classes of filterinputstream and filteroutstream to add the required functions for fileoutstream. 2.2 various types of filterinputstream 2.2.1 are used to encapsulate byte-oriented inputstream1) datainputstream: reads data of basic types (INT, Char, etc.) from stream. 2) bufferedinputstream: buffer zone used 3) linenumberinputstream: records the number of rows in the input stream. You can call getlinenumber () and setlinenumber (INT) 4) pushbackinputstream: rarely used, generally used by the compiler for Development 2.2.2 is used to encapsulate character-oriented inputstream1) and there is no class corresponding to datainputstream. Unless you use bufferedreader when using Readline (), use datainputstream2) bufferedreader: corresponds to bufferedinputstream 3) linenumberreader: corresponds to linenumberinputstream 4) pushbackreader: various types of 2.3 filteroutstream corresponding to pushbackinputstream 2.2.3 are used to encapsulate bytes-oriented outputstream1) dataioutstream: outputs basic data types (INT, Char, etc.) to stream. 2) bufferedoutstream: Use buffer 3) printstream: Generate formatted output 2.2.4 used to encapsulate character-oriented outputstream1) bufferedwrite: corresponds to 2) printwrite: corresponds to 3. randomaccessfile1) You can use the randomaccessfile object to perform read and write operations on the file. 2) when an object is generated, you can specify the nature of the file to be opened: R, read-only; W, write-only; RW can be read and written. 3) You can directly jump to the specified position in the file. 4. an example of I/O application import Java. io. *; public class testio {public static void main (string [] ARGs) throws ioexception {// 1. read data from a file in the unit of Action bufferedreader in = new bufferedreader (New filereade R ("F: // nepalon // testio. Java"); string S, S2 = new string (); While (S = in. Readline ())! = NULL) S2 + = S + "/N"; in. close (); // 1B. received keyboard input bufferedreader stdin = new bufferedreader (New inputstreamreader (system. in); system. out. println ("enter a line:"); system. out. println (stdin. readline (); // 2. read data from a string object stringreader in2 = new stringreader (S2); int C; while (C = in2.read ())! =-1) system. out. println (char) C); in2.close (); // 3. format the data from the memory. Enter try {datainputstream in3 = new datainputstream (New bytearrayinputstream (s2.getbytes (); While (true) system. out. println (char) in3.readbyte ();} catch (eofexception e) {system. out. println ("End of stream");} // 4. output to file try {bufferedreader in4 = new bufferedreader (New stringreader (S2); printwriter out1 = new printwriter (New bufferedwriter (New filewrite R ("F: // nepalon // testio. Out"); int linecount = 1; while (S = in4.readline ())! = NULL) out1.println (linecount ++ ":" + S); out1.close (); in4.close () ;}catch (eofexception ex) {system. out. println ("End of stream");} // 5. try {dataoutputstream out2 = new dataoutputstream (New bufferedoutputstream (New fileoutputstream ("F: // nepalon // data.txt"); out2.writedouble (3.1415926 ); out2.writechars ("/nthas was Pi: writechars/N"); out2.writebytes ("thas was Pi: writebyte/N"); out2.close (); dataIn Putstream in5 = new datainputstream (New bufferedinputstream (New fileinputstream ("F: // nepalon // data.txt"); bufferedreader in5br = new bufferedreader (New inputstreamreader (in5 )); system. out. println (in5.readdouble (); system. out. println (in5br. readline (); system. out. println (in5br. readline ();} catch (eofexception e) {system. out. println ("End of stream");} // 6. use randomaccessfile to operate the file randomaccessfile Rf = new R Andomaccessfile ("F: // nepalon // rtest. dat "," RW "); For (INT I = 0; I <10; I ++) RF. writedouble (I * 1.414); RF. close (); Rf = new randomaccessfile ("F: // nepalon // rtest. dat "," R "); For (INT I = 0; I <10; I ++) system. out. println ("value" + I + ":" + RF. readdouble (); RF. close (); Rf = new randomaccessfile ("F: // nepalon // rtest. dat "," RW "); RF. seek (5*8); RF. writedouble (1, 47.0001); RF. close (); Rf = new randomaccessfile ("F: // nepalo N // rtest. dat "," R "); For (INT I = 0; I <10; I ++) system. out. println ("value" + I + ":" + RF. readdouble (); RF. close () ;}} code explanation (in Zone): in zone 1, when reading a file, read the file content to the cache and call in. readline (), and then read data from the cache in character format (hereinafter referred to as "cache byte read mode "). In section 1B, to read data from the standard I/O (keyboard) as a cache byte, you must first set the standard I/O (system. in) is converted to a character-oriented stream and then encapsulated by bufferedreader. In area 2, a stringreader stream is generated to read data from a string object in the form of characters. In area 4, when reading data from String object S2, the data in the object is first stored in the cache and then read from the buffer; For testio. when operating the out file, the formatted Information is first output to the cache, and then the cached information is output to the file. In Area 5, when outputting the data.txt file, the basic data type is first output to the House cache, and then the cached data is output to the file. when reading the file, first, read the data in the file to the cache, and then read the data in the basic type from the cache. Note the in5.readdouble () line. Because the first writedouble () is written, it must be correctly displayed. It also needs to be read in the form of basic types. In Area 6, files are operated through the randomaccessfile class. ---- Important: linenumberinputstream and stringbufferinputstream have been abolished! Don't use it any more! Stringbufferinputstream, this class does not properly convert characters into bytes! Stringbufferinputstream, deprecated. This class incorrectly assumes that bytes adequately represent characters! ---------------- Caring about Io is the path to your future of Java! ----------------------- The entire Readline () method is not available in the datainputstream stream! Replace it with: bufferedreader d = new bufferedreader (New inputstreamreader (in); -------- convert byte streams into bytes streams and access the cache to read and process the streams! This method has great advantages! --------------------------------------- Why use character streams? ---------------- The primary advantage of character streams is that they make it easy to write programs that are not dependent upon a specific character encoding, and are therefore easy to internationalize. java stores strings in UNICODE, an international standard character encoding that is capable of representing most of the world's written ages. typical user-readable text files, however, US E encodings that are not necessarily related to Unicode, or even to ASCII, and there are supported such encodings. character streams hide the complexity of dealing with these encodings by providing two classes that serve as bridges between byte streams and character streams. the inputstreamreader class implements a character-input stream that reads bytes from a byte-input stream and converts them to Ch Aracters according to a specified encoding. similarly, the outputstreamwriter class implements a character-output stream that converts characters into bytes according a specified encoding and writes them to a byte-output stream. A second advantage of character streams is that they are potentially much more efficient than byte streams. the implementations of runtime of Java's original byte streams are Oriented around byte-at-a-time read and write operations. the character-stream classes, in contrast, are oriented around buffer-at-a-time read and write operations. this difference, in combination with a more efficient locking scheme, allows the character stream classes to make up for the added overhead of encoding conversion in seconds cases. ---------- standard device system. in read data ----------------------------- ---------------------------------------- Read byte: bufferedinputstream read character: bufferedreader + inputstreamreader -------------------------------------------------- import Java. io. *; public class Systemin {public static void main (string ARGs []) {try {// Stream Conversion! Bufferedreader is = new bufferedreader (New inputstreamreader (system. In) string inputline = NULL; while (inputline = is. Readline ())! = NULL) system. out. println (inputline); is. close ();} catch (ioexception e) {system, out. println ("ioxe:" + E) ;}} outputs standard output system. out is a print stream printstream --------------------- import Java. io. *; public class printstandardoutput {public static void main (string [] ARGs) {string myanswer = "no, and that's final,"; system. out. PR Intln ("Hello world of Java"); system. out. println ("the answer is" + myanswer + "at this time. "); printwriter PW = new printwriter (system. out); PW. println ("the answer is" + myanswer + "at this time. "); int I = 42; PW. println (I + '=' + "the answer. "); PW. println ("Note:" + I + '=' + "the answer. "); PW. println (I + "=" + "the answer. "); PW. println (I + ('=' + "the answer. "); PW. close ();}}--------- The handler needs to read (output to-) a text file ------------------------- bufferedreader is = new bufferedreader (New filereader ("XXXX. text "); read bufferedoutputstream byteout = new bufferedoutputstream (New fileoutputstream (" XX. dat "); // write to text! -------------------------------------------------------------- Use bufferedreader -- filereader to read text files! ------------------------ Always pay attention to whether it is a byte stream or a batch stream without importing Java in Io. io. *; import Java. AWT. *; import javax. swing. *; import Java. AWT. event. *; Class filewindow extends jframe implements actionlistener {jtextarea text; bufferedreader in; jbutton button; filereader file; filewindow () {super ("File Upload stream"); Container con = getcontentpane (); tex T = new jtextarea (50, 50); text. setbackground (color. blue); try {file F = new file ("E: // a.txt"); file = new filereader (f); In = new bufferedreader (File ); /** bufferedreader (Reader in) constructor. * The filereader of the file character reading stream is connected to the bufferedreader * stream, so that the object method Readline () of bufferedreader can be used to efficiently read data in a row! */} Catch (filenotfoundexception e) {} catch (ioexception e) {} button = new jbutton ("read"); button. addactionlistener (this); con. setlayout (New borderlayout (); setsize (300,200); setvisible (true); con. add (text, "center"); con. add (button, "South"); addwindowlistener (New windowadapter () {public void windowclosing (invalid wevent e) {setvisible (false); system. exit (0) ;}}) ;}public void action=med (actionevent e) {string s; If (E. getsource () = button) Try {While (S = in. Readline ())! = NULL) text. append (S + '/N'); // here you can also use bufferstring to temporarily Save the read character data !} Catch (ioexception E1) {}}// --------- main () ---------- public static void main (string ARGs []) {filewindow win = new filewindow (); win. pack () ;}----------------- randomaccessfile randomly reads the file --------------- import Java. io. *; public class randomread {final static string filename = "E: // a.txt"; protected string filename; protected randomaccessfile seeker; public static void main (string [] argv) throws ioexception {randomread r = new randomread (filename); system. out. println ("offset is" + R. readoffset (); system. out. println ("message is/" "+ R. readmessage () + "/". ");}/** constructor: Save filename, construct randomaccessfile */Public randomread (string fname) throws ioexception {filename = fname; seeker = new randomaccessfile (fname, "RW");}/** read the offset field, defined to be at location 0 in the file. */Public int readoffset () throws ioexception {seeker. seek (0); seeker. writechars (filename); // move to very beginningreturn seeker. readint (); // and read the offset}/** read the message at the given offset */Public String readmessage () throws ioexception {seeker. seek (120); // move to wherereturn seeker. readline (); // and read the string} is very hard to write. I didn't want to talk about anything, but I still wrote it out in the spirit of being technically responsible. i/O comprehension is a level 3 (if Java Io has 10 levels) with too many errors. unfamiliar with I/O layers Java Io mainly includes Java. io package and Java. NIO package. java. io is mainly extended from four interfaces: Byte: inputstream/outputstream, which is the encapsulation, filtering, and specific implementation class for specific object processing. character: Reader/writer (in the original article, all writer interfaces are written as write, which means you do not understand this interface at all. If you often use the writer interface, how can you tell the difference between writer and write, not a single mistake, but all of them are write) among the above four interfaces, the underlying layer is all the blocked stream of Operation bytes. java. NIO is mainly based on block Operation blocks (buffer). It greatly improves the performance of data output input through the blocking and non-blocking modes that can be set, in addition, the channel can be controlled through the selector mode to achieve multi-user concurrent data transmission in the same output input channel. for example, a socket port can be concurrently accessed by an infinite number of clients (theoretically unlimited. is the classic I/O multiplexing technology.

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.