IO stream other types of streams

 

 

1 Outline:

 

1. Node flow
1, byte array byte node stream
    输入流:ByteArrayInputStream      read(byte[] b, int off, int len)  + close()
    Output stream: ByteArrayOutputStream write(byte[] b, int off, int len) +toByteArray() Do not use polymorphism
2. Processing flow
1. Basic type + String reserved data + type
  Input stream: DataInputStream readXxx
  Output stream: DataOutputStream writeXxx
2. Reference type (object) retains data + type
   Deserialize the input stream: ObjectInputStream readObject()
   Serialize the output stream: ObjectOutputStream writeObject()
  Notice:
1), first serialize and then deserialize; deserialization order must be consistent with serialization
2), not all objects can be serialized, java.io.Serializable
      Not all properties need to be serialized, transient


3. Print Stream PrintStream println() print()
4. Three constants: System.in /out/err System.setIn() setOut() setErr()

 

 

2 codes

 

2.1 Byte stream usage: I don't use it much. I don't know why this api was designed. The operation is the same as that of fileinputstream fileoutputsteam.

 

/**
 * byte array node stream
 * The length of the array is limited, and the amount of data will not be very large
 *
 * The content of the file does not need to be too large
 * 1. File--Program->Byte Array
 * 2. Byte array--Program->File
 *
 *
 *
 * @author Administrator
 *
 */
public class ByteArrayDemo01 {

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		read(write());		
	}
	/**
	 * The output stream operation is somewhat different from the file output stream, there are new methods, and polymorphism cannot be used
	 * @throws IOException
	 */
	public static byte[] write() throws IOException{
		//destination
		byte[] dest;
		//Select the different points of the stream
		ByteArrayOutputStream bos =new ByteArrayOutputStream();
		// operation write out
		String msg = "The operation is consistent with the file input stream operation";
		byte[] info =msg.getBytes();
		bos.write(info, 0, info.length);
		//Get data, create a newly allocated byte array
		dest = bos.toByteArray ();
		// release resources
		bos.close();
		return dest;
		
		
	}
	
	
	
	/**
	 * Input stream operations are consistent with file input stream operations
	 * read byte array
	 * @throws IOException
	 */
	public static void read(byte[] src) throws IOException{
		// data source incoming		
		
		// select stream
		InputStream is =new BufferedInputStream(
					new ByteArrayInputStream(
							src
						)
				);
		//operate
		byte[] flush =new byte[1024];
		int len ​​= 0;
		while(-1!=(len=is.read(flush))){
			System.out.println(new String(flush,0,len));
		}
		// release resources
		is.close();
		
		
		
	}

}

 

/**
 *1, file--program->byte array
 *1), file input stream     
 * byte array output stream
 *
 *
 * 2. Byte array--Program->File
 * 1), byte array input stream
 * file output stream
 * @author Administrator
 *
 */
public class ByteArrayDemo02 {

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		byte[] data =getBytesFromFile("e:/xp/test/1.jpg");
		toFileFromByteArray(data,"e:/xp/test/arr.jpg");
	}
	/**
	 * 2. Byte array--Program->File
	 */
	public static void toFileFromByteArray(byte[] src,String destPath) throws IOException{
		//create source
		//destination
		File dest=new File(destPath);
		
		// select stream
		//byte array input stream
		InputStream is =new BufferedInputStream(new ByteArrayInputStream(src));		
		//file output stream
		OutputStream os =new BufferedOutputStream(new FileOutputStream(dest));
		
		//The operation keeps reading the byte array
		byte[] flush =new byte[1];
		int len ​​= 0;
		while(-1!=(len =is.read(flush))){
			// write to file
			os.write(flush, 0, len);
		}
		os.flush();
		
		// release resources
		os.close();
		is.close();
		
		
	}
	
	
	
	/**
	 * 1. File--Program->Byte Array
	 * @return
	 * @throws IOException
	 */
	public static byte[] getBytesFromFile(String srcPath) throws IOException{
		//create file source
		File src =new File(srcPath);
		//create byte array destination
		byte[] dest =null;
		
		// select stream
		//file input stream     
		InputStream is =new BufferedInputStream(new FileInputStream(src));
		//The byte array output stream cannot use polymorphism
		ByteArrayOutputStream bos =new ByteArrayOutputStream();
		
		
		//The operation keeps reading the file and writing it out to the byte array stream
		byte[] flush =new byte[1024];
		int len ​​= 0;
		while(-1!=(len =is.read(flush))){
			//Write to byte array stream
			bos.write(flush, 0, len);
		}
		bos.flush();
		
		//retrieve data
		dest = bos.toByteArray ();
		
		bos.close();
		is.close();		
		return dest;
	}

}

 

 2.2 DataInputStream DataOutputStream writes out data and types

The official website explains

Data input streams allow applications to read basic Java data types from the underlying input stream in a machine-independent manner. Applications can use the data output stream to write data that is later read by the data input stream

 

Pay attention to the comments in the code. The order of the data written must be consistent with the order of the data types read. This is the same as

When the custom javabean in hadoop is transmitted across machines, the writing and writing are strictly in the same order. I think hadoop is designed with these two classes of javase to achieve.

 

/**
 * Data type (basic + String) processing stream
 * 1. Input stream DataInputStream readXxx()
 * 2. Output stream DataOutputStream writeXxx()
 * New method cannot use polymorphism
 *
 * java.io.EOFException : No related content was read
 * @author Administrator
 *
 */
public class DataDemo01 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			//write("e:/xp/test/data.txt"); // Write both characters and character formats to the disk. At this time, double-clicking the disk file will be garbled because this kind of file is for the computer to see, not for people come to see
			read("e:/xp/test/data.txt");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		}
		
		
		
	}
	/**
	 * Read data + type from file
	 * @throws IOException
	 */
	public static void read(String destPath) throws IOException{
		//create source
		File src =new File(destPath);
		// select stream
		DataInputStream dis =new DataInputStream(
					new BufferedInputStream(
								new FileInputStream(src)
							)
				);
		
		//The order of the operation read is consistent with the write and must exist to read
		//Inconsistent, there is a problem with the data
		long num2 =dis.readLong();
		double num1 =dis.readDouble();
		String str =dis.readUTF();
		
		dis.close();
		System.out.println(num2+"-->"+str);
		
	}
	/**
	 * data + type output to file writes data type and data value to disk
	 * @throws IOException
	 */
	public static void write(String destPath) throws IOException{
		double point =2.5;
		long num=100L;
		String str = "Data Type";
		
		//create source
		File dest =new File(destPath);
		//Select the stream DataOutputStream
		DataOutputStream dos =new DataOutputStream(
					new BufferedOutputStream(
								new FileOutputStream(dest)
							)
				);
		//The order in which the operations are written is ready for reading
		dos.writeDouble(point);
		dos.writeLong(num);
		dos.writeUTF(str);		
		dos.flush();
		
		// release resources
		dos.close();  
	}

}


 

 

/**
 * Data type (basic + String) processing stream
 * 1. Input stream DataInputStream readXxx()
 * 2. Output stream DataOutputStream writeXxx()
 * New method cannot use polymorphism
 *
 * java.io.EOFException : No related content was read
 * @author Administrator
 *
 */
public class DataDemo02 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			byte[] data=write();
			read(data);
			System.out.println(data.length);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		}
		
		
		
	}
	/**
	 * read data + type from byte array
	 * @throws IOException
	 */
	public static void read(byte[] src) throws IOException{
		// select stream
		DataInputStream dis =new DataInputStream(
					new BufferedInputStream(
								new ByteArrayInputStream(src)
							)
				);
		
		//The order of the operation read is consistent with the write and must exist to read
		double num1 =dis.readDouble();
		long num2 =dis.readLong();
		String str =dis.readUTF();
		
		dis.close();
		
		System.out.println(num1+"-->"+num2+"-->"+str);
		
	}
	/**
	 * data + type output to byte array
	 * @throws IOException
	 */
	public static byte[] write() throws IOException{
		// target array
		byte[] dest =null;
		double point =2.5;
		long num=100L;
		String str = "Data Type";
		
		
		//选择流 ByteArrayOutputStream  DataOutputStream
		ByteArrayOutputStream bos =new ByteArrayOutputStream();
		DataOutputStream dos =new DataOutputStream(
					new BufferedOutputStream(
							bunch
							)
				);
		//The order in which the operations are written is ready for reading
		dos.writeDouble(point);
		dos.writeLong(num);
		dos.writeUTF(str);		
		dos.flush();

		dest = bos.toByteArray ();
		
		// release resources
		dos.close();
		
		return dest;
		
		
		
		
	}

}

 

 

 2.3 Serialization and deserialization ObjectOutputStream ObjectInputStream

 

public class Employee implements java.io.Serializable {
	// no need to serialize
	private transient String name;
	private double salary;
	public Employee() {
	}
	public Employee(String name, double salary) {
		super();
		this.name = name;
		this.salary = salary;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getSalary() {
		return salary;
	}
	public void setSalary(double salary) {
		this.salary = salary;
	}
}



/**
 * Not all objects can be serialized java.io.NotSerializableException
 * Not all properties need to be serialized transient
 * @author Administrator
 *
 */
public class ObjectDemo01 {

	/**
	 * @param args
	 * @throws ClassNotFoundException
	 */
	public static void main(String[] args) throws ClassNotFoundException {
		try {
			seri("e:/xp/test/ser.txt");
			read("e:/xp/test/ser.txt");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		}
	}
	//Deserialization maps numbers in the computer world to the human world
	public static void read(String destPath) throws IOException, ClassNotFoundException{
		//create source
		File src =new File(destPath);
		// select stream
		ObjectInputStream dis =new ObjectInputStream(
					new BufferedInputStream(
								new FileInputStream(src)
							)
				);
		
		//The order of the operation read is consistent with the write and must exist to read
		//Inconsistent, there is a problem with the data
		Object obj =dis.readObject();
		if(obj instanceof Employee){
			Employee emp=(Employee)obj;
			System.out.println(emp.getName());
			System.out.println(emp.getSalary());
		}
		
		obj =dis.readObject();
		int[] arr=(int[])obj;
		System.out.println(Arrays.toString(arr));
		dis.close();
	}
	
	//Serialize human-recognized characters to disk
	public static void seri(String destPath) throws IOException{
		Employee emp =new Employee("bjsxt",1000000);
		int[] arr ={1,2,3,45};
		//create source
		File dest =new File(destPath);
		//Select the stream ObjectOutputStream
		ObjectOutputStream dos =new ObjectOutputStream(
					new BufferedOutputStream(
								new FileOutputStream(dest)
							)
				);
		//The order in which the operations are written is ready for reading
		dos.writeObject(emp);
		dos.writeObject(arr);
		// release resources
		dos.close();
	}
}

 

 2.4 Print Stream: Please read the summary of the comment section carefully, the essence is in this   PrintStream 

 

/**
 * PrintStream print stream --> process stream PrintStream adds functionality to other output streams, allowing them to conveniently print various data value representations
   Redirecting output can be done in two ways:
   1 ps = new PrintStream(dest) ;  ps.print(xxx)
   2 System.setOut(PrintStream out) ; System.out.println("a"); The objects returned by System.out System.in System.erro are all PrintStreams, and System.out.println is equivalent to ps.print in 1 above (xxx)
 * @author Administrator
 *
 */
public class PrintStreamDemo01 {

	/**
	 * @param args
	 * @throws FileNotFoundException
	 */
	public static void main(String[] args) throws FileNotFoundException {
		System.out.println("test");
		PrintStream ps =System.out; //
		ps.println(false);
		
		
		// output to file
		File src = new File("e:/xp/test/print.txt");
		ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(src))); // Create a new print stream to output the printed data to the target file
		ps.println("io is so easy....");
		
		ps.close();
	}

}


**
 * three constants
 * 1, System.in input stream keyboard input
 * 2, System.out output stream console output
 *    System.err
 *    
 *==> redirect   
 * setIn ()
 * setOut()
 * setErr()
 * The input stream of the FileDescriptor.in console can be found in System.class
 * The input stream of the FileDescriptor.out console can be found in System.class
 * @author Administrator
 *
 */
public class SystemDemo01 {

	/**
	 * @param args
	 * @throws FileNotFoundException
	   The print stream changes the output mode to a file and then switches back to print to the console
	 */
	public static void main(String[] args) throws FileNotFoundException {
		//test1();
		// test2 ();
		// redirect
		// If true, the output buffer will be flushed whenever a byte array is written, one of the println methods is called, or a newline or byte ('\n') is written
		System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream("e:/xp/test/print.txt")),true));
		System.out.println("a"); //Console -->File		
		System.out.println("test");
		// back to console
		System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(FileDescriptor.out)),true)); // FileDescriptor.in is the standard input stream used by the console
		System.out.println("back....");
	}
	public static void test2() throws FileNotFoundException{
		InputStream is =System.in; //Keyboard input
		is = new BufferedInputStream(new FileInputStream("e:/xp/test/print.txt"));
		Scanner sc = new Scanner(is);
		//System.out.println("Please input:");
		System.out.println(sc.nextLine());
	}
	
	public static void test1(){
		System.out.println("test");
		System.err.println("err");
	}

}

 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326591253&siteId=291194637