Java-I/O operations

Source: Internet
Author: User

I. I/O operation:

Let's look at how the file class is constructed:


Construction Method Summary
File(File parent,String child)
Creates a new instance from the parent abstract path name and child pathname string File .
File(String pathname)
Creates a new instance by converting the given pathname string to an abstract path name File .
File(String parent,String child)
Creates a new instance based on the parent pathname string and the child pathname string File .
File(URI uri)
Creates a new file instance by converting the given file: URI to an abstract path name.


Take a look at the level of the input and output stream:



Starting with an example, you can better understand IO:

1). create File:

public class Iotest {public static void main (string[] args) {File file = new file ("E:/lzr.txt"); try {System.out.println (fi Le.createnewfile ());} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}

Print: True

We'll see a lzr.txt file under the E-drive.

Here first explain \, use in Windows \ can, but in Linux is not possible, because the symbol does not recognize what the meaning, it will be used/to replace. To better cross-platform, the file class provides us with two constants file.separator and File.separatorchar, respectively, that I should use.

public class Iotest {public static void main (string[] args) {File file = new file ("E:" +file.separator+ "Lzr.txt"); try {Syst Em.out.println (File.createnewfile ());} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}


2). Create a folder:

public class Iotest {public static void main (string[] args) {File file = new file ("E:" +file.separator+ "LZR" +file.separator + "LZR"); System.out.println (File.mkdir ()); System.out.println (File.mkdirs ());}}

Print: False True because the middle layer of the folder LZR is not created, so the first method fails, and the second succeeds.

The differences between the two methods are:

mkdir () can only create the last-level folder, which fails if one of the parent directories does not exist.

Mkdirs () includes a non-existent parent directory that is also created.

3). Delete files:

public class Iotest {public static void main (string[] args) {File file = new file ("E:" +file.separator+ "LZR"); System.out.println (File.delete ());}}

Print: True

Recursive implementation delete files under directory:

public class IOTest2 {public static void DeleteFile (file file) {if (File.isfile () | | file.list (). Length = = 0) {file.delete () ;} else{file[] files = file.listfiles (); for (File f:files) {DeleteFile (f); F.delete ();}}} public static void Main (string[] args) {File file = new file ("E:" +file.separator+ "LZR");d eletefile (file);}}

All files under the specified directory are deleted.


4). List all the files in the directory:

public class Iotest {public static void main (string[] args) {        file F=new file ("E:" +file.separator);        Get the name of the file under        string[] filename=f.list ();        for (String name:filename) {            System.out.println (name);        }        Get the file        file[] fileNames = F.listfiles ();        for (File files:filenames) {        System.out.println (Files.getname ());}}}        

Print: omitted here

All the files in your file directory are printed.

For example, we can print out the files in the filter directory, such as for. txt:

public class Iotest {public static void main (string[] args) {        file F=new file ("E:" +file.separator);        Get the name of the file under the        string[] filename=f.list (new FilenameFilter () {@Overridepublic Boolean accept (file dir, String name) { c3/>//to determine if the suffix is the. txt End if (name.endswith (". txt")) {return true;} return false;}        });        for (String name:filename) {            System.out.println (name);}}}        

Print: omitted here ...

The printed result is only a. txt file at the end.


5). Input output stream:

The input and output is relative to the program, the program in the use of data played by the role of two: one is the source, and the other is the purpose. If the program is the source of the data stream, that is, the data provider, this data flow to the program is the output stream. If the program is the destination of the data stream, it is the input stream.

The structure of the stream can be divided into a byte stream (in bytes as a processing unit) and a character stream (in characters as the processing Unit).

The input and output streams of the byte stream are based on the two abstract classes InputStream and Outpurstream, and the input and output operations of the byte stream are implemented by subclasses of these two classes. The character stream input and output base is reader and writer. All input and output streams at the bottom are in the form of a byte stream.

Streams are categorized as node streams and filter classes.

A). Node class: A stream class that reads and writes from a specific place.

b). Filter Flow: Use node stream as input or output. The filtered stream is created using an existing input stream or an output stream connection. The main feature is that the input and output data can be transferred to the data in the specified type or format conversion, you can realize the binary byte data understanding and encoding conversion.

To implement a simple read file (input stream) Example:

public class Inputstreamtest {public static void main (string[] args) throws Exception {InputStream is = new Fileinputstrea M ("E:" +file.separator+ "Lzr.txt"); byte[] buffer = new Byte[100];int length = 0;while ( -1! = (length= (Is.read (buffer,0,100 )) {string str = new String (buffer,0,length); System.out.println (str);} Is.close ();}}

Print:

Asdf

Zxcv

Qwer

Tyui
Implement an example of a write file (output stream):

public class Outputstreamtest {public static void main (string[] args) throws Exception {        file F=new file ("E:" +file.sep arator+ "Hello.txt");        OutputStream out =new FileOutputStream (f);        String str= "Hello!";        Byte[] B=str.getbytes ();        Out.write (b);        Out.close ();}}
Open File: Hello!

You must remember to close the stream after you open it, otherwise it will always be a resource.

Wrapping an output stream (buffered stream):

public class Bufferedoutputstreamtest {public static void main (string[] args) throws Exception {outputstream os = new File OutputStream ("Lzr.txt");//buffer stream Bufferedoutputstream BOS = new Bufferedoutputstream (OS); Bos.write ("www.baidu.com". GetBytes ()); Bos.close ();}}

Refresh the next item, there will be more than one Lzr.txt file open in the directory to see the content.

When the buffer is written full or the output stream is closed, it is output to the stream at once, or the flush () method is used to actively output the buffer to the stream.


6). Byte array output stream:

public class Bytearrayoutputstreamtest {public static void main (string[] args) throws Exception {Bytearrayoutputstream ba OS = new Bytearrayoutputstream (); String str = "Hello World Welcome", byte[] b = str.getbytes (); Baos.write (b); byte[] B2 = Baos.tobytearray (); for (int i = 0;i& lt;b2.length;i++) {System.out.println ((char) b2[i]);} OutputStream OS = new FileOutputStream ("test.txt"); Baos.writeto (OS); Baos.close (); Os.close ();}}


7). Basic Type Output stream:

public class Datastreamtest {public static void main (string[] args) throws Exception {DataOutputStream dos = new DATAOUTPU TStream (New Bufferedoutputstream (New FileOutputStream ("Data.txt")); int i = 10;char ch = ' a '; byte B = 1;dos.writebyte (b); Dos.writeint (i);d os.writechar (CH);d os.close ();}}

The basic type of output stream with buffering. The display is a bunch of garbled characters because it is not a string to save.
8). Basic type Input stream:

public class Datastreamtest {public static void main (string[] args) throws Exception {//dataoutputstream dos = new Dataout Putstream (New Bufferedoutputstream (New FileOutputStream ("Data.txt"));//int i = 10;//char ch = ' a ';//byte B = 1;//dos.wri Tebyte (b);//dos.writeint (i);//dos.writechar (ch);//dos.close ();D atainputstream dis = new DataInputStream (new Bufferedinputstream (New FileInputStream ("Data.txt")));//To read data as stored data System.out.println (Dis.readbyte ()); System.out.println (Dis.readint ()); System.out.println (Dis.readchar ());d is.close ();}}

Output: 1 A


The other input and output streams can be found on the JDK, which is only part of the story. To know one other basic is almost.





Java-I/O operations

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.