欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ByteArrayStream & DataStream & InputStream & FileStream 博客分类: java.io java.ioFileStreamByteArrayStreamDatatStream 

程序员文章站 2024-03-16 20:11:58
...

 

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();
			}
		}
	}
}