ByteArrayStream & DataStream & InputStream & FileStream

 

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class StreamTest {
	
	public static void main(String[] args) {
		
		File file = new File("test.txt");
		
		/**
		 * Output Stream
		 */
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataOutputStream dos = new DataOutputStream(fos);
		
		String[] strings = {"apple", "banana", "cup"};
		int[] ints = {10, 11, 12};
		double[] doubles = {10.11, 11.11, 12.11};
		
		try {
			for (int i = 0; i<3; i++) {
				dos.writeUTF("BEGIN");
				dos.writeUTF(strings[i]);
				dos.writeInt(ints[i]);
				dos.writeDouble(doubles[i]);
			}
				
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				dos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		try {
			fos.write(baos.toByteArray());
		} catch (IOException e1) {
			e1.printStackTrace();
		} finally {
			try {
				baos.close();
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		/**
		 * Input Stream
		 */
		InputStream is = null;
		try {
			is = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		byte[] buf = new byte[1024];
		int len = 0;
		int temp = 0;
		
		try {
			while ((temp = is.read()) != -1) {
				buf[len] = (byte) temp;
				len ++;
			}
			is.read(buf, 0, len);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		//byte array stream, input
		ByteArrayInputStream bais = new ByteArrayInputStream(buf);
		DataInputStream dis = new DataInputStream(bais);
		
		try {			
			for (int j=0; j<3; j++) {
				dis.readUTF();
				String s = dis.readUTF();
				int i = dis.readInt();
				double d = dis.readDouble();
				
				System.out.print("s = " + s + "\n");
				System.out.print("i = " + i + "\n");
				System.out.print("d = " + d + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				dis.close();
				bais.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
 

 

你可能感兴趣的:(java.io,filestream,ByteArrayStream,DatatStream)