Java IO stream byte stream, java IO stream byte

Source: Internet
Author: User

Java IO stream byte stream, java IO stream byte
I. Common file Operations

 

File file = new File ("E: \ test \ javaIo"); System. out. println (file. isDirectory (); // determines whether the file is a directory (if the file does not exist, false is returned) System. out. println (file. isFile (); // determines whether the file is a specific file System. out. println (file. exists (); // determines whether the file exists in System. out. println (file. mkdir (); // create a directory and return the boolean Type System. out. println (file. delete (); // delete a file or directory. the return value belongs to the boolean Type System. out. println (file. mkdirs (); // create a multi-level directory and return the boolean type File fileF = new File ("E: \ test \ javaIo", "1.txt"); fileF. createNewFile (); // create the file fileF. delete (); // delete the file System. out. println (file. getAbsolutePath (); // obtain the absolute file path E: \ test \ javaIo System. out. println (file. getName (); // get the file name javaIo System. out. println (file. getParent (); // obtain the parent file path E: \ test System. out. println (file. getParentFile (); // get the parent file object

 

/*** List all files in the specified directory (including subdirectories) * @ param file */public static void directoryList (File dir) {if (! Dir. exists () {throw new IllegalArgumentException ("directory" + dir + "does not exist");} if (! Dir. isDirectory () {throw new IllegalArgumentException (dir + "not a directory");} // String [] file = dir. list (); // obtain the names of all directories and files under the directory (returns a string array) File [] files = dir. listFiles (); // obtain the file object if (files! = Null & files. length> 0) {for (File file: files) {if (file. isDirectory () {// recursively operate directoryList (file) if it is a directory;} else {System. out. println (file. getName ());}}}}

 

Ii. byte stream and byte stream

Byte stream: the byte stream processing unit is 1 byte. It operates byte and byte arrays and mainly processes binary data. Therefore, byte streams can be used to process any type of objects. Byte streams operate on the file itself (data changes can be seen if we do not call the close () or flush () method for file read/write operations ). Byte streams are mainly used to operate byte data. The byte array prevails. The main operation classes are OutputStream and InputStream.

The stream can be divided into read/write streams (input/output streams) based on the role or flow direction: Read (input) stream InputStream; write (output stream) OutputStream.

Input (read): reads data from a disk (File) into the memory.

Output (write): writes data in memory to a disk (file.

Byte stream: the byte stream processing unit is 2 Unicode characters, operating characters, character arrays, or strings respectively. The Bytes stream is a string of Unicode characters that are converted into two bytes by the Java Virtual Machine. The swap stream operates on the buffer (data changes cannot be seen if we do not call the close () or flush () method for file read/write operations ).

Note: All files are stored in bytes. On the disk, the reserved characters are not the characters of the files, but are first encoded into bytes, and then stored on the disk. When reading a file (especially a text file), it is also a byte read to form a byte sequence.

3. InputStream)

Input: read data from the disk into the memory.

The InputStream abstract class is a superclass that represents all classes of the byte input stream. Applications that need to define the subclass of InputStream must always provide the method to return the next input byte.

Public abstract class InputStream implements Closeable {private static final int MAX_SKIP_BUFFER_SIZE = 2048; // maximum buffer size // reads data of one byte and returns the data read. If-1 is returned, it indicates public abstract int read () throws IOException at the end of the input stream; // read a certain number of bytes from the input stream and store them in byte array B, returns the actual number of bytes read. If-1 is returned, it indicates public int read (byte B []) throws IOException {return read (B, 0, B. length);} // read the data into a byte array and return the actual number of bytes to read. If-1 is returned, the data is read to the end of the input stream. Off specifies the starting offset position for storing data in array B, len specifies the maximum number of bytes to read public int read (byte B [], int off, int len) throws IOException {} // skip and discard n data bytes in the input stream. Public long skip (long n) throws IOException {} // The estimated number of bytes that the next method call of the input stream can read or skip from the input stream without blocking. Public int available () throws IOException {return 0;} // close the input stream and release all system resources associated with the stream. Public void close () throws IOException {} // mark the current position in the input stream. Public synchronized void mark (int readlimit) {}// locate the stream to the position when the mark method is called for the input stream. Public synchronized void reset () throws IOException {throw new IOException ("mark/reset not supported");} // test whether the input stream supports the mark and reset methods. Public boolean markSupported () {return false ;}}

FileInputStream reads the file content:

1 public class InputStreamTest {2 public static void main (String [] args) throws IOException {3 readOne (); 4 readByte (); 5} 6 // public abstract int read () throws IOException 7 // The next byte that reads data from the input stream. Returns the int byte value between 0 and 255. If no byte is available because it has reached the end of the stream, the return value is-1. 8 // This method is blocked until the input data is available, the end of the stream is detected, or an exception is thrown. 9 public static void readOne () throws IOException {10 InputStream is = new FileInputStream ("E: \ javaTest \ 1.txt"); 11 int by = 0; 12 while (by = is. read ())! =-1) {13 System. out. println (char) by); // convert to char type 14} 15 is. close (); 16} 17 // public int read (byte [] B) throws IOException18 // read a certain number of bytes from the input stream, and store it in the buffer array B. Returns the actual number of bytes read as an integer. 19 // This method is blocked until the input data is available, the end of the file is detected, or an exception is thrown. 20 public static void readByte () throws IOException {21 InputStream is = new FileInputStream ("E: \ javaTest \ 1.txt"); 22 byte [] bytes = new byte [1024]; 23 int len = 0; 24 while (len = is. read (bytes ))! =-1) {25 System. out. println (new String (bytes, 0, len); 26} 27 is. close (); 28} 29}View Code

BufferedInputStream byte input (read) buffer stream

Byte streams read and write an array at a faster speed than reading and writing a byte at a time. This is because the array buffering effect is added, this situation (decorative design mode) is also taken into account by the java design itself, so it provides a byte buffer stream (BufferedInputStream ). The stream only provides a buffer, designed to improve read/write efficiency. The basic Stream object is required for file operations. BufferedInputStream is a subclass of InputStream that has all parent classes.

1     public static void bufferedInputStreamTest() throws IOException{2         BufferedInputStream bis=new BufferedInputStream(new FileInputStream("E:\\javaTest\\5.txt"));3         byte [] bytes=new byte[1024];4         int len=0;5         while((len=bis.read(bytes))!=-1){6             System.out.println(new String(bytes,0,len));7         }8         bis.close();9     }

 

4. byte output stream)

Output: Write Data in the memory to the disk file.

The OutputStream class is the base class of all output streams in the Java io api. It mainly inputs data in the memory into the target media.

Public abstract class OutputStream implements Closeable, Flushable {// write a byte to the stream public abstract void write (int B) throws IOException; // write all data in the byte array to the output stream public void write (byte B []) throws IOException {write (B, 0, B. length);} // write the data of the length bytes starting from the offset to the output stream. Public void write (byte B [], int off, int len) throws IOException {} // The method clears all data written to OutputStream to the Target media, even if all data is written to FileOutputStream, the data may still be stored in the memory buffer. By calling the flush () method, you can refresh the data in the buffer to the disk public void flush () throws IOException {} // when Data Writing ends, you need to disable OutputStream public void close () throws IOException {}}

FileOutputStream writes data to a file

Function creation: FileOutputStream (String name, boolean append) creates an output file stream that writes data to a file with a specified name. (Append data to the end of the file)
FileOutputStream (String name) creates an output file stream that writes data to a file with the specified name. (Re-write at the beginning of the file)

1 // write (byte [] B) convert B. length bytes are written to the output stream from the specified byte array. 2 public static void writeByte () throws IOException {3 OutputStream OS = new FileOutputStream ("E: \ javaTest \ 1.txt "); 4 String str = "China"; 5 OS. write (str. getBytes (); 6 // flush () refresh the output stream and forcibly write all buffered output bytes. 7 OS. flush (); 8 // close () 1. Change the stream object to spam, so that the jvm garbage collection mechanism can be easily recycled. 2. Notify the system to release resources related to the file. 9 OS. close (); 10} 11 // write (int B) writes the specified byte to this output stream. 12 public static void writeInt () throws IOException {13 OutputStream OS = new FileOutputStream ("E: \ javaTest \ 1.txt "); 14 // we all know that the computer disk stores binary data. Here, 97 is written to the disk as the underlying binary data. When we open a file through notepad, 15 // the file will be decoded Based on the ASCII code table. Therefore, we can see the character "a" 16 OS. write (97); 17 OS. flush (); 18 OS. close (); 19} 20 // write (byte [] B, int off, int len) writes the len bytes starting from offset off in the specified byte array to this output stream. 21 public static void writeOffLen () throws IOException {22 OutputStream OS = new FileOutputStream ("E: \ test \ javaIo \ 1.txt "); 23 byte [] bytes = "China ". getBytes (); 24 OS. write (bytes, 0, bytes. length); 25 OS. flush (); 26 OS. close (); 27}View Code

 BufferedOutputStream byte output (write) buffer stream

Byte streams read and write an array at a faster speed than reading and writing a byte at a time. This is because the array buffering effect is added, this situation (decorative design mode) is also taken into account by the java design itself, so it provides a byte buffer stream (BufferedOutputStream ). The stream only provides a buffer, designed to improve read/write efficiency. The basic Stream object is required for file operations. BufferedOutputStream is a subclass of OutputStream that has all parent classes.

Public static void bufferOutPutStreamTest () throws IOException {BufferedOutputStream bos = new BufferedOutputStream (new FileOutputStream ("E: \ javaTest \ 5.txt"); bos. write ("medium ". getBytes (); bos. flush (); bos. close ();}

 

V. Use of byte input stream and byte output stream

Use the basic byte stream for file copy:

 1 public  static void readWriter() throws IOException{ 2         String readFileName="D:"+File.separator+"html"+File.separator+"1.txt"; 3         String writerFileName="D:"+File.separator+"html"+File.separator+"2.txt"; 4         InputStream is=new FileInputStream(new File(readFileName));// 5         OutputStream out=new FileOutputStream(new File(writerFileName)); 6         byte [] b=new byte[1024]; 7         int len=0; 8         while((len=is.read(b))!=-1){ 9             out.write(b, 0, len);10         }11         is.close();12         out.close();13     }

Use byte buffer streams to copy files:

 1 public static void BufferFileCopy() throws IOException{ 2         BufferedInputStream bis=new BufferedInputStream(new FileInputStream("E:\\javaTest\\5.txt")); 3         BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("E:\\javaTest\\6.txt")); 4         byte[]bytes=new byte[1024]; 5         int len=0; 6         while((len=bis.read(bytes))!=-1){ 7             bos.write(bytes, 0, len); 8         } 9         bos.flush();10         bos.close();11         bis.close();12     }

 

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.