2. Familiar with Java Basic Class Library series--java IO class Library

Source: Internet
Author: User

the commonly used IO operations in Java can be divided into four parts: file class operation, Randomaccessfile class operation, Byte stream operation, character stream operation. as long as you master all the examples listed in this article, basically for the Java IO Stream operation can be said to be mastered.

The following are examples of the operations that are commonly used in the four parts, in the form of junit test cases.

First, the file class operation

The file class operation defines the most basic operations related to the robust system of the operating system, and can perform a series of operations on folders and files.

1. Some common usage

       1. Two constants @test public void Twoconstant () {//output: '/' ': ' System.out.println (File.separator); System.out.println (file.pathseparator);} 2. Create a new file @test public void CreateFile () {File F = new file ("Hello"); Try{f.createnewfile (); SYSTEM.OUT.PRINTLN ("Created file:" + F.getabsolutepath ());} catch (Exception e) {e.printstacktrace ();}} 3. Create a folder @test public void CreateFolder () {try{file file = new file ("Hellofolder") and////when there is no directory or file corresponding to that name in a directory, To establish this folder if (!file.isdirectory () &&!file.isfile ()) {File.mkdir ();//file.mkdirs ();//If the parent directory does not exist, create a parent directory together} Else{system.out.println ("File or folder with this name already exists");}} catch (Exception e) {e.printstacktrace ();}} 4. Delete a file @test public void DeleteFile () {try{file file = new file ("Hello"), if (File.exists ()) {File.delete ();} ELSE{SYSTEM.OUT.PRINTLN ("File does not exist");}} catch (Exception e) {e.printstacktrace ();}} 5. Delete a folder (same as delete file) @Test public void DeleteFolder () {try{file file = new file ("Hellofolder"); if (File.exists ()) { File.delete ();} Else{system.out.println ("The folder does not exist");}} catch (Exception e) {E.printstackTrace ();}}  6. Get file names (including hidden files and folders) for all files in the specified directory @Test public void Getallfilename () {Try{file folder = new File ("."); Current directory string[] filestrs = Folder.list (); for (String str:filestrs) {System.out.print (str + "");}} catch (Exception e) {e.printstacktrace ();}}  7. Get the path to all files in the specified directory @test public void Getallfilepath () {Try{file folder = new File ("."); Current directory file[] files = folder.listfiles (); for (File file:files) {System.out.println (File.getcanonicalpath ());}}     catch (Exception e) {e.printstacktrace ();}}

2. Print all files in the specified directory (recursive invocation)

Package com.chanshuyi.io;/** * Lists the full contents of the specified directory * */import java.io.*;class listallfile{public    static void Main (string[] A RGS) {        file F = new File (".");        Print (f);    }        Recursively print public    static void print (File f) {    if (f! = null) {    if (f.isdirectory ()) {    file[] Filearray = F.listfiles ();    if (Filearray! = null) {for    (int i = 0; i < filearray.length; i++) {    print (filearray[i]);}}    } else{    System.out.println (f);}}}    

Second, Randomaccessfile class operation

The Randomaccessfile class can randomly access a file, such as the ability to specify a read-write pointer to a byte, or a read-write pointer that specifies the number of bytes skipped. Simply put, the Randomaccessfile class provides a number of methods that allow us to read and write files in more detail.

//8. Random Read-write file class @test public void Operaterandom () {try{//1. Skips two bytes to read the contents of the file// The contents of the file are: Hello, this is demo file.randomaccessfile randomrw = new Randomaccessfile (new file ("Demo.txt"), "RW");  Randomrw.skipbytes (2); Skips two bytes, skipping ' he ' two English characters (one English character occupies 1 bytes) byte b[] = new Byte[100];int length = Randomrw.read (b); System.out.println ("read a total of" + length + "bytes, read the content is:" + new String (b));//Read the total 23 bytes, read the content is: Llo, the IS demo FILE.//2. Read and write pointers Jump back to the head of the file to reread Randomrw.seek (0); length = Randomrw.read (b); System.out.println ("read a total of" + length + "bytes, read the content is:" + new String (b));//Read a total of 25 bytes, read the content is: Hello, the is demo FILE.//3. Get read The address where the pointer is written is long pointer = Randomrw.getfilepointer ();  SYSTEM.OUT.PRINTLN ("File pointer address:" + pointer); File pointer address: 25randomrw.seek (2);p ointer = Randomrw.getfilepointer (); SYSTEM.OUT.PRINTLN ("File pointer address:" + pointer);//File pointer address: 2randomrw.seek ();p ointer = Randomrw.getfilepointer (); SYSTEM.OUT.PRINTLN ("File pointer address:" + pointer);//File pointer address: 77randomrw.close ();} catch (Exception e) {e.printstacktrace ();} 

Third, the word throttle read and write

Fileinputstream/fileoutputstream-Read and write operations for files

Objectinpustream/objectoutputstream-Read and write operations on serialized objects are implemented

Bytearrayinputstream/bytearrayoutputstream-Read and write operations on byte arrays are implemented

Pipedinputstream/pipedoutputstream-Enables communication between different threads

Sequenceinputstream-Implement merging of different input streams (This object does not have a corresponding OutputStream class)

Bufferedinputstream/bufferedoutputstream-Implementing a read-write cache layer

1. Byte stream read-bytes (indicates the data type read is Byte or byte[])

15. Byte stream read-byte@test public void ReadByte () {try{file file = new file ("Hello.txt"); InputStream fos = new FileInputStream ( file); byte[] bytes = new byte[fos.available ()];fos.read (bytes); String str = new string (bytes); System.out.println ("file content is: \ n" + str); Fos.close ();} catch (Exception e) {e.printstacktrace ();}}

2, Byte stream read (cache)-byte

BYTE stream read (cache)-Byte@test public void Writebytewithbuffere () {try{file file = new file ("Hello1.txt"); OutputStream fos = new F Ileoutputstream (file); Bufferedoutputstream out = new Bufferedoutputstream (FOS); Out.write ("Hello \ n". GetBytes ()); Out.write ("Eat!". GetBytes ()); Out.flush (); Fos.close ();} catch (Exception e) {e.printstacktrace ();}}

3. Byte stream Write-bytes

17. Byte Stream write-byte@test public void WriteByte () {try{file file = new file ("Hello.txt"); OutputStream fos = new Fileoutputstre AM (file); Fos.write ("Hello mac.\n Hi, Mac.") GetBytes ()); Fos.close ();} catch (Exception e) {e.printstacktrace ();}}

4, Byte stream write (cache)-byte

18. Byte stream Write (cache)-Byte@test public void Writebytewithbuffer () {try{file file = new file ("Hello.txt"); OutputStream fos = new FileOutputStream (file); Bufferedoutputstream BOS = new Bufferedoutputstream (FOS); Bos.write ("Hello mac.\n Hello, Mac.".) GetBytes ()); Bos.close (); Fos.close ();} catch (Exception e) {e.printstacktrace ();}}

If you have carefully knocked over the above 4 examples of code you will find, in fact, like the byte stream read and write, as if the cache and no cache, their code seems to be similar ah, at least the same time to write data. while the read of a character stream is added to the cache layer, at least the entire row of data can be read directly, and after the write of the character stream is cached, a newline character can be written. What is the necessity of that byte-stream cache?

Indeed, there is no difference between the code and its methods, but from the official API documentation, one of the most important things about caching is reducing the number of IO times the program has on disk. A cached program reads a number of bytes at a time and is then available to the program, but if you do not cache it, the program reads only the number of bytes specified in the code. When you read data from a file in a byte-by-byte, the difference is apparent. If you do not use the cache for data reading, then you read a byte of data, the program will go to the disk to read a file, which will cause the disk's frequent IO read, reduce the life of the disk.

5. Objectinputstream/objectoutputstream-Serializes an object

The Pojo object to be serialized:

Package Com.chanshuyi.io.po;import Java.io.serializable;public Class Student implements serializable{/** * Serialization ID */ Private static final Long Serialversionuid = 7288449352920655248l;private string name;private int age;private string phone ;p ublic Student () {}public Student (string name, int age, String phone) {this.name = Name;this.age = Age;this.phone = phone;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;} Public String Getphone () {return phone;} public void Setphone (String phone) {this.phone = phone;} Public String toString () {return name + ', ' + Age + ', ' + Phone;}}

The serialized Pojo object needs to implement the serializable interface.

To serialize an object method:

20.ObjectOutputStream-Serialize Object-Save object properties @test public void serialized () {try{student std = new Student ("Tommy", 13, "189 23923876 "); ObjectOutputStream oos = new ObjectOutputStream (New FileOutputStream (" Studentobject.obj ")); O Os.writeobject (STD); oos.close ();} catch (Exception e) {e.printstacktrace ();}}

To deserialize a method of an object:

21.ObjectInputStream-Deserialization Object-reads the serialized object @test public void deserialized () {Try{objectinputstream ois = new OBJECTINPUTST Ream (New FileInputStream ("Studentobject.obj")); Student std = (Student) ois.readobject (); SYSTEM.OUT.PRINTLN (STD); ois.close ();} catch (Exception e) {e.printstacktrace ();}}

6, Bytearrayinputstream/bytearrayoutputstream-operation memory byte data

19.ByteArrayInputStream-Memory Operation Stream-converts memory data to stream @test public void Random2stream () {try{string str = "Hello"; Bytearrayinputstream input = new Bytearrayinputstream (Str.getbytes ()); Bytearrayoutputstream output = new Bytearrayoutputstream (), int temp = 0;while ((temp = Input.read ())! = ( -1)) {char ch = (CH AR) temp;output.write (character.tolowercase (CH));} String outputstr = output.tostring (); Input.close (); Output.close (); System.out.println (OUTPUTSTR);} catch (Exception e) {e.printstacktrace ();}}

7, Pipedinputstream/pipedoutputstream-to achieve pipeline communication between processes

Receiver:

Package Com.chanshuyi.io.pinestream;import java.io.pipedinputstream;/** * Pipeline Flow-Receiver * @author Yurongchan * */public class Receiver Implements runnable{private PipedInputStream in = Null;public receiver () {in = new PipedInputStream ();} Public PipedInputStream Getin () {return this.in;} public void Run () {byte[] b = new Byte[1000];int length = 0;try{length = This.in.read (b);} catch (Exception e) {e.printstacktrace ();} System.out.println ("received message:" + new String (b, 0, length));}}

Sent by:

Package Com.chanshuyi.io.pinestream;import java.io.pipedoutputstream;/** * Pipeline Flow-Sender * @author Yurongchan * */public class Send Implements Runnable{private pipedoutputstream out = Null;public Send () {out = new PipedOutputStream ();} Public PipedOutputStream Getout () {return this.out;} public void Run () {String msg = "Hello, i ' m outputer.\n Hello, I am the sender." "; Try{out.write (Msg.getbytes ()); Out.close ();} catch (Exception e) {e.printstacktrace ();}}}

Test method:

22.PipedInputStream-Communication between different threads @test public void Pipecontact () {try{send send = new Send (); Receiver receiver = new receiver (); Try{send.getout (). Connect (Receiver.getin ());} catch (Exception e) {e.printstacktrace ();} New Thread (send). Start (); new Thread (receiver). Start (); catch (Exception e) {e.printstacktrace ();}}

8. Sequenceinputstream-Merge input stream

23.SequenceInputStream-Merges several input streams @test public void Sequenceinputstream () {Try{inputstream is1 = new FileInputStream (new File ("Sequence1.txt")), InputStream Is2 = new FileInputStream (New File ("Sequence2.txt")); OutputStream OS = new FileOutputStream (New File ("Sequence3.txt")); Sequenceinputstream sis = new Sequenceinputstream (is1, is2); int temp = 0;while ((temp = Sis.read ())! =-1) {os.write (temp);} Sis.close (); Is1.close (); Is2.close (); Os.close ();} catch (Exception e) {e.printstacktrace ();}}

Then open Sequence3.txt will find that 1, 2 text in the content is in the sequence3.txt.

Iv. character Stream Reading and writing

The read and write of a character stream is actually based on byte stream, and the array is stored more in bytes, so it is more time to read and write with the stream.

So for the character stream to read and write, we only need to master a few common operations can be.

Inputstreamreader/outputstreamwriter-Reading and writing of character streams

Bufferedreader/bufferedwriter-cache layer that implements a character stream

Filereader/filewriter-a tool class for character streams

1. Character Stream read-char (indicates read data type is char or char[])

9. Character Stream read-char@test public void Writechar () {try{InputStreamReader reader = new InputStreamReader (New FileInputStream    ("OutputStreamWriter.txt"));    char[] chars = new char[1000];    int length = Reader.read (chars);    SYSTEM.OUT.PRINTLN ("altogether read" + length + "characters, the content is:" + new String (chars));  Reader.close ();  }catch (Exception e) {e.printstacktrace (); }}

2, character stream read (cache)-Char

10. Character Stream read (cache) @Test public void Writecharwithbuffer () {Try{inputstreamreader ISR = new InputStreamReader (new FileInputStream ("BufferedWriter.txt")); BufferedReader reader = new BufferedReader (ISR); String str = ""; while (str = reader.readline ()) = null && str.length ()! = 0) {System.out.println (str);} Reader.close ();} catch (Exception e) {e.printstacktrace ();}}

3, character stream write-char/char[]/String

11. The character stream is written @Test public void ReadChar () {try{OutputStreamWriter writer = new OutputStreamWriter (New FileOutputStream ("Ou  TputStreamWriter.txt "));  Writer.write ("Allfiletest.filereadutil-character stream write file"); Writer.close ();} catch (Exception e) {e.printstacktrace ();}}

4, character stream write (cache)-char/string

12. Character stream write (cache) @Test public void Readcharwithbuffer () {Try{outputstreamwriter OSW = new OutputStreamWriter (new FileOutputStream ("BufferedWriter.txt")); BufferedWriter writer = new BufferedWriter (OSW); Writer.write ("Allfiletest.filereadutil-character stream write file"); Writer.newline ();//NewLine Writer.write ("second row"); Writer.close ();} catch (Exception e) {e.printstacktrace ();    }}

Summarize the above four ways of writing a stream of characters, we will find two laws, one is the law of reading and writing, one is the law of the buffer layer:

· Read and write laws. a character stream is read, and the data it reads is a single or array of char (character type). A character stream can also be written directly to a string type, except that it can write to a single or multiple char type.

· caching layer rules. Reading and writing of a character stream, an obvious difference after the cache layer is added is that, after adding the cache layer (buffer), the character stream reads can implement the whole line read (ReadLine), and the character stream write can write a newline character (WriteLine).

5. file Reading Tool class

13.FileReader-The file Read Tool class (this is cached.) But it can also be cached) @Test public void Filereadutil () {    Try{filereader fr = new FileReader (New File ("Demo.txt")); BufferedReader reader = new BufferedReader (FR); String str = ""; while ((str = Reader.readline ())! = null && str.length ()! = 0) {System.out.println (str);} Reader.close ();} catch (Exception e) {e.printstacktrace ();}}

Comparing this example to the 2nd example above, which adds a cache of character stream reads, you will find that the difference between the two examples is just a statement of the difference between FileReader and InputStreamReader. Declaring FileReader only needs to add the file type argument, whereas declaring InputStreamReader requires a FileInputStream class before it can keep up with the file type parameters. Therefore, we say that FileReader is a file-reading tool class.

6. File Writing Tool class

14.FileWriter-File Write tool class (this is cached.) But it can also be cached) @Test public void Filewriteutil () {try{filewriter FW = new FileWriter (New File ("FileWriteUtil1.txt")); BufferedWriter writer = new BufferedWriter (FW), Writer.write ("HelloMan1"); Writer.newline (); Writer.write ("HelloMan2" ); Writer.close ();} catch (Exception e) {e.printstacktrace ();}}

In fact, FileWriter and OutputStreamWriter are just the difference between statements.

V. Other

Here are some examples that are not commonly used but are sometimes used, and can be quickly queried when encountered.

1. Append New content

9. Byte stream-Append new content//Whether it is a byte stream or a character stream, to append new content is specified in the FileOutputStream second parameter is true@test public void AppendFile () {Try{file File = new File ("Hello.txt"); OutputStream fos = new FileOutputStream (file, true); String str = "\ n This is the newly added content"; Fos.write (Str.getbytes ()); Fos.close ();} catch (Exception e) {e.printstacktrace ();}}

2. Analog print Stream output data

18. Print stream-simulates how the print output data @test public void PrintStream () {Try{printstream print = new PrintStream (new FileOutputStream (New Fi Le ("PrintStream.txt")));p Rint.println (True);p rint.println ("Hello, I am the print output stream");p rint.printf ("name:%s. Age:%d", "Tom", 32); Format output print.close ();//The data here will be PrintStream.txt in the file to see}catch (Exception e) {e.printstacktrace ();}}

3. Use OutputStream to output content to the screen

19. Use OutputStream to output content to the screen @test public void Systemoutstream () {Try{outputstream out = system.out;out.write ("Hello". GetBytes ()); Out.close ();} catch (Exception e) {e.printstacktrace ();}}

4. Standard output redirection

20. Standard output redirect @test public void Redirectoutput () {try{system.out.println ("Print Hello "); System.setout (New PrintStream (New FileOutputStream (New File ("RedirectOutput.txt")));// The output below will be redirected to the file System.out.println ("= = = Redirected Output = = ="); System.out.println ("Hello, Eclipse in Mac.");} catch (Exception e) {e.printstacktrace ();}}

5. Standard input redirection

21. Standard input REDIRECT @test public void Redirectinput () {try{file file = new file ("RedirectOutput.txt"); if (!file.exists ()) { SYSTEM.OUT.PRINTLN ("file does not exist!"); return;} Else{system.setin (new FileInputStream), byte b[] = new Byte[1000];int length = System.in.read (b); SYSTEM.OUT.PRINTLN ("read-in content:" + new String (b, 0, length));}} catch (Exception e) {e.printstacktrace ();}}

6. Error output redirection

22. Error output redirection @test public void Redirecterroutput () {try{system.err.println ("Print" on the screen. Hello "); System.seterr (New PrintStream (New FileOutputStream (New File ("RedirectErrOutput.txt")));// The output below will be redirected to the file System.err.println ("= = = Redirected Error Output = = ="); System.err.println ("Hello, Eclipse in Mac.");} catch (Exception e) {e.printstacktrace ();}}

Thanks to the following blog post for reference:

1, http://www.cnblogs.com/rollenholt/archive/2011/09/11/2173787.html

2, http://www.cnblogs.com/oubo/archive/2012/01/06/2394638.html

2. Familiar with Java Basic Class Library series--java IO class Library

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.