Use Java byte stream

InputStream is the Java parent class for all input stream of bytes, the OutputStream is the parent class for all Java byte output stream class, which is an abstract class, subclass thus inherits they want to redefine the abstract parent class.

The following describes the first two common methods to provide the parent class, and how to use them subclasses of input and output stream of bytes, including type ByteArrayInputStream, ByteArrayOutputStream type, class and the FileInputStream class FileOutputStream.

Input stream of bytes

InputStream class and its subclasses the object representation input stream of bytes, commonly subclass InputStream class is as follows.

	ByteArrayInputStream 类:将字节数组转换为字节输入流,从中读取字节。
	
	FileInputStream 类:从文件中读取数据。
	
	PipedInputStream 类:连接到一个 			PipedOutputStream(管道输出流)。
	
	SequenceInputStream 类:将多个字节输入流串联成一个字节输入流。
	
	ObjectInputStream 类:将对象反序列化。

InputStream class using one or a batch method may read bytes from the stream.

InputStream class common method

Method name and return value type Explanation
int read() A stream read from the input 8-bit bytes, and converts it to an integer of 0 to 255, and finally returns the integer. Return -1 indicates that has come to the end of the input stream. In order to improve the efficiency of I / O operations, we recommended to use the read () method of the other two forms
int read(byte[] b) Several bytes read from the input stream, and save them to the parameter b specifies a byte array. The method returns the number of bytes read. Return -1 indicates the end of the input stream has reached the
int read(byte[] b, int off, int len) Several bytes read from the input stream, and save them to the parameter b specifies a byte array. Wherein, off starts saving the designated starting index data in the byte array; len specify the number of bytes read. The method returns the number of bytes actually read. Return -1 indicates the end of the input stream has reached the
void close() Closes the input stream. After the read operation is complete, you should turn off the input stream, the system will release relevant to this input stream resources. Note, InputStream class itself close () method does not do anything, but many of its subclass overrides the close () method
int available() Returns the number of bytes that can be read from the input stream
long skip(long n) Skip parameter n specifies the number of bytes from the input stream. The method returns the number of bytes to skip
void mark(int readLimit) Start flag is set at the current position of the input stream, readLimit parameter specifies the maximum number of bytes is set labeled
boolean markSupported() Determines whether the current flag is set to allow the input stream, it returns true, false otherwise
void reset() The input stream pointer to the start of the return flag is set to

note: Before using the mark () method and reset () method, you need to determine whether the file system supports both methods.

Byte output stream

Object OutputStream class and its subclasses represents an output stream of bytes. Common subclass of OutputStream follows.

	ByteArrayOutputStream 类:向内存缓冲区的字节数组中写数据。
	
	FileOutputStream 类:向文件中写数据。
	
	PipedOutputStream 类:连接到一个 		PipedlntputStream(管道输入流)。
	
	ObjectOutputStream 类:将对象序列化。

Using OutputStream class or method can be written to a number of bytes from the stream.

Common method of OutputStream

Method name and return value type Explanation
void write(int b) Write a byte to the output stream. Where the arguments is of type int, but it allows the use of the expression, without cast to type byte. In order to improve the efficiency of I / O operations, it is recommended to make use of write () method of the other two forms
void write(byte[] b) The parameter b specifies all the bytes in the array of bytes written to the output stream
void write(byte[] b,int off,int len) The parameter b specifies a number of bytes in the array of bytes written to the output stream. Wherein, off the specified byte array starting index, len denotes the number of elements
void close() Close the output stream. After the write operation is complete, it should close the output stream. The system will release resources associated with the output stream. Note, OutputStream class itself close () method does not do anything, but many of its subclass overrides the close () method
void flush() To improve efficiency, when data is written to the output stream, the data will normally saved to the memory buffer, the buffer only when the data reaches a certain level, data in the buffer will be written to the output stream . Use flush () method may be forced to buffer the data written to the output stream, and to empty the buffer

Byte array input stream

ByteArrayInputStream class data can be read from the byte array in memory, the following two class constructor overloads .

	ByteArrayInputStream(byte[] buf):创建一个字节数组输入流,字节数组类型的数据源由参数 buf 指定。
	
	ByteArrayInputStream(byte[] buf,int offse,int length):创建一个字节数组输入流,其中,参数 buf 指定字节数组类型的数据源,offset 指定在数组中开始读取数据的起始下标位置,length 指定读取的元素个数。

Use ByteArrayInputStream class implements an array of bytes read from the data, and then converted to an int and output. code show as below:

public class test {
    public static void main(String[] args) {
        byte[] b = new byte[] { 1, -1, 25, -22, -5, 23 }; // 创建数组
        ByteArrayInputStream bais = new ByteArrayInputStream(b, 0, 6); // 创建字节数组输入流
        int i = bais.read(); // 从输入流中读取下一个字节,并转换成int型数据
        while (i != -1) { // 如果不返回-1,则表示没有到输入流的末尾
            System.out.println("原值=" + (byte) i + "\t\t\t转换为int类型=" + i);
            i = bais.read(); // 读取下一个
        }
    }
}

In the embodiment, the input stream of bytes 4 bytes bais to start reading a first element from the element b byte array, and converts it to an int 4 bytes of data, and finally returns.

prompt: In addition to the above example to print the value of i, but also print out the value (byte) i, since the value of i is the conversion of data from the byte type over, so use (byte) i can obtain the original data byte.

Operating results of the program are as follows:

原值=1   转换为int类型=1
原值=-1   转换为int类型=255
原值=25   转换为int类型=25
原值=-22   转换为int类型=234
原值=-5   转换为int类型=251
原值=23   转换为int类型=23

From the results, after conversion to an int type data byte 1 and data 255 and 234 becomes -22, interpretation of this result is as follows:

	字节类型的 1,二进制形式为 00000001,转换为 int 类型后的二进制形式为 00000000 00000000 0000000000000001,对应的十进制数为 1。
	
	字节类型的 -1,二进制形式为 11111111,转换为 int 类型后的二进制形式为 00000000 00000000 0000000011111111,对应的十进制数为 255。

Seen from the conversion into the number of bytes of type int type, if it is positive, then the value unchanged; if it is negative, since the conversion, directly in front of complement binary form of 0 24, thus changing the original represented negative twos complement form, it changes the value, i.e., becomes positive.

prompt: Binary form negative in the presence of complement form , such as -1, which in binary form is come: first acquired primitive 000,000,011, followed by anti-code operation, into 0,0 1 becomes 1, so that to give 11111110, finally complement operation, it is at the end of the inverted bits plus 1, so that it becomes 11,111,111.

ByteArrayOutputStream

ByteArrayOutputStream class can write to the byte array in memory, there are two class constructor overloads it follows.

	ByteArrayOutputStream():创建一个字节数组输出流,输出流缓冲区的初始容量大小为 32 字节。
	
	ByteArrayOutputStream(int size):创建一个字节数组输出流,输出流缓冲区的初始容量大小由参数 size 指定。

In addition to the class ByteArrayOutputStream output stream of bytes common methods described in the foregoing, two other methods are as follows.

	intsize():返回缓冲区中的当前字节数。
	
	byte[] toByteArray():以字节数组的形式返回输出流中的当前内容。

ByteArrayOutputStream implemented using class byte array data output, the code is shown below.

public class Test {
    public static void main(String[] args) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] b = new byte[] { 1, -1, 25, -22, -5, 23 }; // 创建数组
        baos.write(b, 0, 6); // 将字节数组b中的前4个字节元素写到输出流中
        System.out.println("数组中一共包含:" + baos.size() + "字节"); // 输出缓冲区中的字节数
        byte[] newByteArray = baos.toByteArray(); // 将输出流中的当前内容转换成字节数组
        System.out.println(Arrays.toString(newByteArray)); // 输出数组中的内容
    }
}

The output of the program are as follows:

数组中一共包含:6字节
[1, -1, 25, -22, -5, 23]

File input stream

Java FileInputStream stream is commonly used as a comparison, which retrieves input bytes from a file in the file system. FileInputStream can be accessed by using a byte file, a group of bytes or the entire file.

When you create an object FileInputStream class, if you can not find the file specified will throw FileNotFoundException exception, which must be captured or throw statement.

FileInputStream conventional construction methods are mainly the following two overloaded forms.

	FileInputStream(File file):通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的 File 对象 file 指定。
	
	FileInputStream(String name):通过打开一个到实际文件的链接来创建一个 FileInputStream,该文件通过文件系统中的路径名 name 指定。

Example the FileInputStream () method of using two configuration.

try {
    // 以File对象作为参数创建FileInputStream对象
    FileInputStream fis1 = new FileInputStream(new File("F:/mxl.txt"));
    
    // 以字符串值作为参数创建FilelnputStream对象
    FileInputStream fis2 = new FileInputStream("F:/mxl.txt");
} catch(FileNotFoundException e) {
    System.out.println("指定的文件找不到!");
}

Suppose we have a D: \ myJava \ HelloJava.java file, using the following FileInputStream class reading and outputting the contents of the file. code show as below:

public class Test {
    public static void main(String[] args) {
        File f = new File("D:/myJava/HelloJava.java");
        FileInputStream fis = null;
        try {
            // 因为File没有读写的能力,所以需要有个InputStream
            fis = new FileInputStream(f);
            // 定义一个字节数组
            byte[] bytes = new byte[1024];
            int n = 0; // 得到实际读取到的字节数
            System.out.println("D:\\myJava\\HelloJava.java文件内容如下:");
            // 循环读取
            while ((n = fis.read(bytes)) != -1) {
                String s = new String(bytes, 0, n); // 将数组中从下标0到n的内容给s
                System.out.println(s);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

As the above code, the main FileInputDemo class () method first creates a File object F, the object point D: \ myJava \ HelloJava.java file. Then a FileInputStream objects created using the constructor FileInputStream fis class, and declare a length of 1024 byte array type, and then uses the FileInputStream the read () method reads the data file to HelloJava.java byte array in bytes, and outputs the data. And finally close the input stream FileInputStream finally statement.

D: \ myJava \ HelloJava.java document reads as follows:

/*
*第一个java程序
*/
public class HelloJava {
    // 这里是程序入口
    public static void main(String[] args) {
        // 输出字符串
        System.out.println("你好 Java");
    }
}

note: FileInputStream class overrides the parent class InputStream read () method, skip () method, available () method and the close () method does not support mark () method and reset () method.

File output stream

OutputStream FileOutputStream class inherits from class, rewrite and implements all the methods in the parent class. The object represent a class FileOutputStream file output stream of bytes to be written into a byte or group of bytes to the stream. When you create an object FileOutputStream class, if the specified file does not exist, create a new file; if the file already exists, clear the contents of the original file rewritten.

FileOutputStream constructor class are mainly the following four overloads.

	FileOutputStream(File file):创建一个文件输出流,参数 file 指定目标文件。
	
	FileOutputStream(File file,boolean append):创建一个文件输出流,参数 file 指定目标文件,append 指定是否将数据添加到目标文件的内容末尾,如果为 true,则在末尾添加;如果为 false,则覆盖原有内容;其默认值为 false。
	
	FileOutputStream(String name):创建一个文件输出流,参数 name 指定目标文件的文件路径信息。
	
	FileOutputStream(String name,boolean append):创建一个文件输出流,参数 name 和 append 的含义同上。

note: Use constructor FileOutputStream (String name, boolean append) creates a file output stream object, it will be data appended to the end of the existing file. The string name specified in the original document, if only for the additional data instead of overwriting any existing data, append Boolean type parameter should be true.

A file output stream following four instructions:
1. destination file specified in the constructor of the class FileOutputStream destination file may not exist.

2. The name of the destination file may be arbitrary, for example, D: \ abc, D: \ abc.de and D: \ abc.de.fg so you can, you can use tools such as Notepad to open and view the contents of these files .

3. The target directory where the file must exist, otherwise it will throw an exception java.io.FileNotFoundException.

4. The name of the file can not be an existing directory. Such as the D drive existing Java folder, you can not use Java as the file name that you can not use D: \ Java, java.io.FileNotFoundException otherwise throw an exception.

Read D: \ myJava \ content HelloJava.java file, where the use FileInputStream class implementation, then write the contents of the new file D: \ myJava \ HelloJava.txt in. Specific code as follows:

public class Test {
    public static void main(String[] args) {
        FileInputStream fis = null; // 声明FileInputStream对象fis
        FileOutputStream fos = null; // 声明FileOutputStream对象fos
        try {
            File srcFile = new File("D:/myJava/HelloJava.java");
            fis = new FileInputStream(srcFile); // 实例化FileInputStream对象
            File targetFile = new File("D:/myJava/HelloJava.txt"); // 创建目标文件对象,该文件不存在
            fos = new FileOutputStream(targetFile); // 实例化FileOutputStream对象
            byte[] bytes = new byte[1024]; // 每次读取1024字节
            int i = fis.read(bytes);
            while (i != -1) {
                fos.write(bytes, 0, i); // 向D:\HelloJava.txt文件中写入内容
                i = fis.read(bytes);
            }
            System.out.println("写入结束!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close(); // 关闭FileInputStream对象
                fos.close(); // 关闭FileOutputStream对象
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

As the above code, the D: \ content myJava \ HelloJava.java file is written to the document D via the input / output streams: \ myJava \ HelloJava.txt file. Because HelloJava.txt file does not exist, so in the implementation of this program will create a new file and write the content.

Run the program, after the success will output "write end!" In the console. At this point, open the D: \ myJava \ HelloJava.txt file will find its contents with the contents of the file HelloJava.java same.

prompt: When you create a FileOutputStream object, if the append parameter is set to true, you can add data to the end of the contents of the target file, then the target file can still exist temporarily.

Published 457 original articles · won praise 94 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_45743799/article/details/104709438