java基础之I/O流

java基础之I/O流

一.概述

    1.1 简介

       系统(这里能够理解为CPU)和不一样的设备设备交换数据都是经过物理上的I/O总线。在java中交换数据通常分为2步,第一步联通设备(File和Url),确承认以使;第二版就是经过I/O流交互数据。这样记忆,第一步就是修路,第二版就是拉货。 路通了,才能让车一次次拉货。java

    1.2 I/O流图

        a) 字节流:spa

        b) 字符流:
code

        

    c) 总结
对象

        1. 字节流操做对象:byteArray,file,piped,object,string(如今建议在字符流方式操做)
ip

        2.字符流操做对象:charArray,file,string
get

        3.字节流-》字符流类:inputStreamReader、OutputStreamWriter
input

        4.处理类:BufferedInputStream,DataInputStream,BufferedReader。若是说input、read是最小单位处理,则处理类就是对其加强,加快处理的方式。
string

        5.在使用完后必定要把 input/output、reader/writer都关闭it

二.实例

    2.1 字节流的

/**
	 * byteArray:读取字节流
	 * 
	 * @throws IOException
	 */
	@Test
	public void getByteArrayInputStream() throws IOException {
		String io = "d:\\project\\test\\1231.txt";
		byte b[] = io.getBytes();
		InputStream is = new ByteArrayInputStream(b);
		
		int readbyte;
		while ((readbyte = is.read()) != -1) {
			System.out.println(readbyte);
		}
		Reader r=new InputStreamReader(is);
	}
	
	
	
	/**
	 * 文件io 文件流修改的读取使用了 native方法
	 * 
	 * @throws IOException
	 */
	public void getFileInputStream() throws IOException {
		File file = new File("d:\\project\\test\\1231.txt");
		InputStream is = new FileInputStream(file);
		int readbyte;
		while ((readbyte = is.read()) != -1) {
			System.out.println(readbyte);
		}
	}

	/**
	 * stringinputStream 过时
	 * 
	 * @throws IOException
	 */
	public void getStringInputStream() throws IOException {
		String io = "d:\\project\\test\\1231.txt";
		InputStream is = new StringBufferInputStream(io);
		int readbyte;
		while ((readbyte = is.read()) != -1) {
			System.out.println(readbyte);
		}
	}

    2.2 字符流

/**
	 * reader : file、string、charArray都会将数据转化为byte
	 * 
	 * @throws IOException
	 */
	@Test
	public void StringReader() throws IOException {
		String io = "d:\\project\\test\\1231.txt";
		Reader r = new StringReader(io);
		int temp;
		while ((temp = r.read()) != -1) {
			System.out.println(temp);
		}

	}

	@Test
	public void BufferReader() throws IOException {
		String io = "d:\\project\\test\\1231.txt";
		BufferedReader r = new BufferedReader(new StringReader(io));
		String temp = null;
		while ((temp = r.readLine()) != null) {
			System.out.println(temp);
		}
	}

    3.3 压缩

@Test
	public void zipTest() throws IOException {
		/**
		 * @see 将D:\project\test下的3个文件,压缩到 my.zip中
		 */
		File directory = new File("d:\\project\\test");
		String zipFileName = "my.zip";// 压缩文件的名字
		ZipOutputStream os = new ZipOutputStream(new FileOutputStream(new File("d:\\project", zipFileName)));
		InputStream is = null;
		for (File fs : directory.listFiles()) {
			is = new FileInputStream(fs);
			int fileByte;
			os.putNextEntry(new ZipEntry(fs.getName()));// 建立一个压缩文件中的文件
			while ((fileByte = is.read()) != -1) {
				os.write(fileByte);
			}
		}
		os.close();
		is.close();
	}
}
相关文章
相关标签/搜索