Java-IO stream byte stream, javaio stream byte

Source: Internet
Author: User

Java-IO stream byte stream, javaio stream byte

IO streams (input streams and output streams) are also divided into byte streams and bytes streams.

A stream is the source or destination of data stored on a disk or other peripheral devices.

Input stream: The program reads data sources from the input stream. Data sources include external sources (keyboards, files, networks, etc ...), It is the communication channel that reads the data source into the program.

Output stream: The program writes data to the output stream. Output Data in the program to the outside world (display, printer, file, network ...) .

  • Byte stream

1. InputStream and OutputStream

InputStream abstracts how an application reads data.

OutputStream abstracts the way an application writes data.

2. Read the end of the file, called EOF = end. Read-1 to the end.

3. Basic input stream method

Int B = in. read (); read a byte, unsigned to the lower eight bits of the int.-1 is EOF

Int. read (byte [] buf) read data to fill in the byte array buf

Int. read (byte [] buf, int start, int size) read data to fill in the byte array buf, from the start position of the buf to store size data

4. Basic Method of output stream

Out. write (int B); write a byte to the stream, which is eight bits of B.

Out. write (byte [] buf); write the buf byte array to the stream

Out. write (byte [] buf, int start, int size); byte array buf writes size bytes to the stream from the start position

5. FileInputStream is a subclass of InputStream. It specifically implements reading data from files.

6. FileOutputStream is a subclass of OutputStream and implements the writing of byte data to the file.

Demo of FileInputStream:

Package com. test. io; import java. io. bufferedInputStream; import java. io. bufferedOutputStream; import java. io. file; import java. io. fileInputStream; import java. io. fileOutputStream; import java. io. IOException; public class IOUtils {/*** read the content of the specified file, output to the console in hexadecimal format * and 10 byte line breaks per output * @ param fileName * @ throws IOException */public static void printHex (String fileName) throws IOException {// read the file as a byte stream. UtStream in = new FileInputStream (fileName); int B; int I = 1; while (B = in. read ())! =-1) {if (B <= 0xf) {System. out. print ("0");} System. out. print (Integer. toHexString (B) + ""); if (I % 10 = 0) {System. out. println ("");} I ++;} in. close ();} public static void printhexbytearray (String fileName) throws IOException {FileInputStream in = new FileInputStream (fileName); byte [] buf = new byte [20*1024]; // If the byte array is large enough, you can read the byte array in batches from the in, put it into the buf byte array, and put it at most from the first position. length. The returned value is read. The number of bytes/* int bytes = in. read (buf, 0, buf. length); int j = 1; for (int I = 0; I <bytes; I ++) {if (buf [I] <= 0xf) {System. out. print ("0");} System. out. print (Integer. toHexString (buf [I] & 0xff) + ""); if (j % 10 = 0) {System. out. println ("");} j ++;} * // If the byte array is not large enough, you cannot read int bytes = 0 at a time; int j = 1; while (bytes = in. read (buf, 0, buf. length ))! =-1) {for (int I = 0; I <bytes; I ++) {if (buf [I] <= 0xf) {System. out. print ("0");} System. out. print (Integer. toHexString (buf [I] & 0xff) + ""); if (j % 10 = 0) {System. out. println ("") ;}j ++ ;}}}}

Demo of FileOutputStream:

Package com. test. io; import java. io. fileOutputStream; import java. io. IOException; public class FileOutputDemo {public static void main (String [] args) throws IOException {// if the file does not exist, create it directly. If yes, delete it and create it. (If the second parameter is true, the byte is written to the end of the file instead of the start of the file .) FileOutputStream out = new FileOutputStream ("F: \ javaio \ out. dat "); out. write ('A'); // write the lower eight bits of 'A' (write only one byte at A time) int A = 10; out. write (a >>> 24); out. write (a >>> 16); out. write (a >>> 8); out. write (a); byte [] B = "10 ". getBytes (); out. write (B); out. close (); IOUtils. printHex ("F :\\ javaio \ out. dat ");}}

7. DataOutputStream and DataInputStream. With the extension of the stream function, data of int, long, and character types can be read more conveniently.

Package com. test. io; import java. io. dataOutputStream; import java. io. fileOutputStream; import java. io. IOException; public class DataOutputDemo {public static void main (String [] args) throws IOException {String file = "F: \ javaio \ B .txt "; dataOutputStream dos = new DataOutputStream (new FileOutputStream (file); dos. writeInt (10); dos. writeInt (-10); dos. writeLong (10l); dos. writeDouble (1, 10.5); dos. writeUTF ("hello"); dos. writeChars ("China"); dos. close (); IOUtils. printHex (file );}}

Running result:

00  00  00  0a  ff  ff  ff  f6  00  00  00  00  00  00  00  0a  40  25  00  00  00  00  00  00  00  06  e4  bd  a0  e5  a5  bd  4e  2d  56  fd  

Where,00 06The two bytes are the number of Chinese characters "hello.

package com.test.io;import java.io.DataInputStream;import java.io.FileInputStream;import java.io.IOException;public class DataInputDemo {    public static void main(String[] args) throws IOException {        String file = "F:\\javaio\\b.txt";        DataInputStream dis = new DataInputStream(new FileInputStream(file));        int i = dis.readInt();        System.out.println(i);        i = dis.readInt();        System.out.println(i);        long l = dis.readLong();        System.out.println(l);        double d = dis.readDouble();        System.out.println(d);        String s = dis.readUTF();        System.out.println(s);        dis.close();    }}

Running result:

10-101010.5 hello

8. bufferedInputStream & BufferedOutputStream, these two stream classes provide IO with buffer operations. Generally, when opening a file for write or read operations, a buffer is added. This stream mode improves IO performance.

File copy:

Package com. test. io; import java. io. bufferedInputStream; import java. io. bufferedOutputStream; import java. io. file; import java. io. fileInputStream; import java. io. fileOutputStream; import java. io. IOException; public class IOUtils {/*** copy an object, byte batch read * @ param srcFile source File * @ param destFile target File * @ throws IOException */public static void copyFile (File srcFile, File destFile) throws IOException {if (! SrcFile. exists () {throw new IllegalArgumentException ("file" + srcFile + "nonexistent");} if (! SrcFile. isFile () {throw new IllegalArgumentException (srcFile + "not a file");} FileInputStream in = new FileInputStream (srcFile); FileOutputStream out = new FileOutputStream (destFile ); bytes [] buf = new byte [10*1024]; int B; while (B = in. read (buf, 0, buf. length ))! =-1) {out. write (buf, 0, B); out. flush (); // It is recommended that you refresh the output stream and forcibly write all buffered output bytes.} In. close (); out. close ();}/*** copy a File and use a buffer byte stream * @ param srcFile * @ param destFile * @ throws IOException */public static void copyFileByBuffer (File srcFile, file destFile) throws IOException {if (! SrcFile. exists () {throw new IllegalArgumentException ("file" + srcFile + "nonexistent");} if (! SrcFile. isFile () {throw new IllegalArgumentException (srcFile + "not a file");} FileInputStream in = new FileInputStream (srcFile); FileOutputStream out = new FileOutputStream (destFile ); bufferedInputStream bis = new BufferedInputStream (in); BufferedOutputStream bos = new BufferedOutputStream (out); int c; while (c = bis. read ())! =-1) {bos. write (c); bos. flush ();} bis. close (); bos. close ();}/*** copy the File and read the * @ param srcFile * @ param destFile * @ throws IOException */public static void copyFileByByte (File srcFile, file destFile) throws IOException {if (! SrcFile. exists () {throw new IllegalArgumentException ("file" + srcFile + "nonexistent");} if (! SrcFile. isFile () {throw new IllegalArgumentException (srcFile + "not a file");} FileInputStream in = new FileInputStream (srcFile); FileOutputStream out = new FileOutputStream (destFile); int c; while (c = in. read ())! =-1) {out. write (c); out. flush () ;}in. close (); out. close ();}}

Test file copy:

package com.test.io;import java.io.File;import java.io.IOException;public class IOUtilsTest {    public static void main(String[] args) {        //IOUtils.printHex("D:\\javaProgram\\Hello.java");        try {            long start = System.currentTimeMillis();            //IOUtils.copyFile(new File("F:\\javaio\\1.mp3"), new File("F:\\javaio\\2.mp3"));//211ms            //IOUtils.copyFileByBuffer(new File("F:\\javaio\\1.mp3"), new File("F:\\javaio\\3.mp3"));//18583ms            IOUtils.copyFileByByte(new File("F:\\javaio\\1.mp3"), new File("F:\\javaio\\4.mp3"));//37822ms            long end = System.currentTimeMillis();            System.out.println(end - start);        } catch (IOException e) {            e.printStackTrace();        }    }}

According to the test above, the fastest way to copy a file is to read it in batches by byte.

 

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.