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();
	}
}
相關文章
相關標籤/搜索