Java IO Basics

Source: Internet
Author: User

Java IO Basics

@author Ixenos

Summary: Creating files, file filters, stream classifications, flow structures, common streams, using file streams

How to create a file

#当我们调用File类的构造器时, you simply create a file object at run time instead of creating one in the file system. The file class can represent a directory or file that exists in the filesystem, or it can indicate a

#File. Separator is a cross-platform delimiter (win with "\", while "\" also do the inverse of the character, so "\ \" to represent the delimiter; UNIX with "/")

1. Call the CreateNewFile () method of the File object
1 classfiletest1{2      Public Static voidMain (string[] args) {3File testfile =NewFile ("C:\\test");4System.out.println (Testfile.getabsolutepath () + "presence" +testfile.exists ());5 6         Try{7Testfile.createnewfile ();//Create a file8}Catch(IOException e) {9 e.printstacktrace ();Ten         } One  ASystem.out.println (Testfile.getabsolutepath () + "presence" +testfile.exists ()); -  -         //Test Catalog Creation mkdirs () theFile TestDir =NewFile ("c:\\a\\b\\c"); -System.out.println (Testfile.getabsolutepath () + "presence" +testfile.exists ()); -  - testdir.mkdirs (); +System.out.println (Testfile.getabsolutepath () + "presence" +testfile.exists ()); -     } + } A  at------------------------------------- -C:\Test is present:false -  -C:\Test is present:true -  -C:\a\b\c is present:false in  -C:\a\b\c is present:true
View Code 2. Using the FileOutputStream constructor

File Object files Filtering #public string[] List ()//equivalent to filter = = NULL

if this abstract path name does not represent a directory, this method returns null . Otherwise, a string array is returned, with each array element corresponding to each file or directory in the directory.

Indicates that the name of the directory itself and its parent directory are not included in the results.

Each string is a file name, not a full path.

It is not guaranteed that the same strings in the resulting array will appear in a particular order, especially if they are not guaranteed to appear in alphabetical order.

#public string[] List (filenamefilter filter)

#boolean Accept (File dir, String name) is an abstract method in the FilenameFilter interface

This method behaves the same as the method except that the string in the returned array must satisfy the filter list() .

If given filter null , all names are accepted. Otherwise, FilenameFilter.accept(java.io.File, java.lang.String) true The name satisfies the filter only if the method that invokes the filter on the file name or directory name in this abstract pathname and its represented directory is returned.

* Here, Filenamefileter can be likened to Invocationhandler, and accept is like invoke

1ImportJava.io.*; 2 3/**4 * Face FilenameFilter Interface Programming 5*/6 Public classFileextensionfilterImplementsfilenamefilter{7PrivateString Extension =NULL;//File Expansion name8 Publicfileextensionfilter (String extension) {9 This. Extension =extension;10     }11 12/**13 * Define filter rule: End With XXX * The Accept method is called by the list and iterates over the array 15 * Parameters: File Dir represents the files object of the current directory, with a String na Me indicates that the current file name is*/18 Public BooleanAccept (File dir, String name) {File tmp =NewFile (dir, name);20if(Tmp.getname (). toLowerCase (). Endwith (extension)) {21streturn true;22         }23return false;24     }25 26 Public Static voidMain (string[] args) {File CurrentDirectory =NewFile (".");28//constructing a file filter objectFileextensionfilter Javafilter =NewFileextensionfilter ("Java");30 31//list Filters A string object that matches a condition and returns a string array (not guaranteed to have a natural order)string[] Javafiles =currentdirectory.list (javafilter);33 34 for(inti=0; i<javafiles.length; i++){35System.out.println (Javafiles[i]);36         }37     }38}
Public string[] List (filenamefilter filter)

What are the categories of streams?

1. different data units can be processed into: character stream, byte stream

2. Data flow direction is different, can be divided into: input stream, output stream

3. different functions, can be divided into: node flow , processing flow (filter flow)

According to the function classification, you can understand this:

node stream : A node stream reads and writes data from a specific data source. That is, a node stream is a stream of directly manipulating files, networks, and so on, such as FileInputStream and FileOutputStream, that they read directly from a file or write to a file.

Process Flow : "Connect" provides a more powerful read and write function for a program by processing the data on top of an existing stream (either a node stream or a processing stream). The filter flow is created using an existing input stream or output stream connection, which is a series of wrappers for the node stream. For example, Bufferedinputstream and Bufferedoutputstream, which are constructed using existing node streams, provide buffered reads and writes, improve read and write efficiency, and DataInputStream and DataOutputStream, Constructed using a node stream that already exists, providing the ability to read and write basic data types in Java. They all belong to the filter stream.

  Processing flow (filter flow) is the idea of decorative mode , the function of the decorative mode extension object , different from the proxy mode is the function of the extended class

Flow Structure Introduction

All stream classes in Java are in the Java.io package, each inheriting from the following four abstract stream types

BYTE stream Character Stream
Input stream InputStream Reader
Output stream OutputStream Writer

1. The units that inherit the stream data from Inputstream/outputstream are bytes (byte=8bit), the darker is the node stream, and the light is the processing stream.

2. The units of the stream data that inherit from Reader/writer are characters (the number of bytes per unit is counted in encoded format, such as UTF-8), the darker is the node stream, and the light is the processing stream.

Introduction to common flow classes

1. Common types of node streams are:

1) Fileinputstream/fileoutputstream of byte streams for file operations

2) Filereader/filewriter of character streams for file manipulation

2. Common types of processing streams are:

1) Buffered stream : buffer stream to "socket" on the corresponding node stream, read and write data to provide a buffer function, improve the reading and writing efficiency, colleagues added some new methods.

Byte buffer stream has bufferedinputstream/bufferedoutputstream, character Buffer stream has bufferedreader/bufferedwriter, The character buffer stream provides methods for reading and writing a row, respectively, ReadLine and newline methods.

For the output buffer stream, the data is written to memory first, and then the Flush method is used to brush the data in memory to the hard disk. Therefore, when using the character buffer stream, be sure to flush first, and then close to avoid data loss.

2) Conversion stream : used for conversion between byte data and character data.

only character Stream inputstreamreader/outputstreamwriter. Among them, InputStreamReader need with InputStream "socket", OutputStreamWriter need with OutputStream "socket".

3) Data Flow : Provides the ability to read and write basic data types in Java.

DataInputStream and DataOutputStream inherit from InputStream and OutputStream, respectively, and require "sockets" on the InputStream and OutputStream types of node streams.

4) Object Flow : Used to write the object directly.

The Stream class has ObjectInputStream and ObjectOutputStream, itself these two methods are nothing, but the object to be written is required, the object must implement the Serializable interface, to declare that it can be serialized. Otherwise, the object stream cannot be read and written.

5) keyword transient, because the adornment implements the properties of the Serializable interface class, the property that is decorated by the modifier, the field is ignored when it is output in the way of object flow.

File stream using Streams

File read and write is the most common I/O operation, through the file stream to connect disk files, read and write file contents

1. file Read and write workflow:

1) Open file input stream or output stream

FileInputStream implements a read file, the constructor that invokes FileInputStream can open a file input stream:

1  Public throws filenotfoundexception//Specify file name 2  Public throws filenotfoundexception//Specify a File object 3  Public FileInputStream (FileDescriptor fdobj)//requires a file descriptor object

FileDescriptor http://www.fengfly.com/plus/view-214059-1.html

If you attempt to open a file input stream on a nonexistent file, the constructor throws an exception filenotfoundexception, which is a subclass of IOException

  most commonly used : Open a file output stream by file name try{fileinputstream fin = new FileInputStream ("Readme.txt");} catch (IOException e) {...}

2) file read or write operations

FileInputStream

1  Public native int throws IOException 2  Public int Read (bytethrows  ioexception3publicint read (byteintintthrows IOException

If for some reason the file is unreadable, the Read method throws IOException

3) close file input stream or output stream

1  ...2  finally{3      Try{4          //because in the finally module, if the file does not exist, there is no flow, so there is a null pointer to determine5          if(Fin! =NULL){6 fin.close ();7           } 8}Catch(Exception e) {}9  }Ten  ...   One------------------------------- A because close () can also produce an exception, the code is more miscellaneous -You can use try-with-resources to automatically close the flow http://www.cnblogs.com/ixenos/p/5701679.html

4) FileInputStream corresponding to the FileOutputStream implementation of the file output function

1  Public throws FileNotFoundException 2  Public Boolean throws FileNotFoundException

(1) when the first constructor is called, if the file specified by name does not exist, the file is created and an output stream is established, and if present, the contents of the file are overwritten

(2) when the second constructor is called, the second parameter append specifies whether to overwrite the existing file, and if Append is true, the new content is added at the end of the file, and if False, the contents of the file are overwritten

(3) FileOutputStream constructor can create a new file at the same time, open an output stream to write, which is not createnewfile () of the file object

Write Public voidWritebyte[] B,intoff,intlen)throwsIOException will specifybyteThis output stream is written to the Len byte of the array starting at offset off. The general contract for write (b, off, Len) is to write some bytes in array b sequentially to the output stream; element B[off] is the first byte written by this operation, b[off+len-1] is the last byte written by this operation. The Write method of the OutputStream invokes the write method of a parameter on each byte to be written out. It is recommended that subclasses override this method and provide a more efficient implementation. If B isNULL, the NullPointerException is thrown. If off is negative, or Len is negative, or off+Len is greater than the length of array B, the indexoutofboundsexception is thrown. Parameter: b-data. Off-the initial offset in the data. Len-The number of bytes to write.
Api-outputstream-write
Write  Public void Write (byte[] b)           throws  ioexception    byte The array is written to this output stream. The general contract for write (b) is: Write with the call (b,0– If an I/O error occurs.
api-outputstream-writes

Java IO Basics

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.