java的IO之字節流

1.文件流: 顧名思義,程序和文件打交道

此時我們談及的文件,值得是純文本文件(txt的,不要使用Word,Excel),
----------------------------------------------------------------- 
在字節流中,暫時不要使用中文.
FileInputStream:     文件的字節輸入流
FileOutputStream:  文件的字節輸出流




2.文件拷貝操作和資源的正確關閉

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class IODemo {
	public static void main(String[] args) {
		//test1();
		test2();
	}
	//原始的拷貝,需要釋放資源,很麻煩
	private static void test1() {
		InputStream in = null;
		OutputStream out = null;
		try {
			//創建源
			in = new FileInputStream("a.txt"); //需要先準備一個a.txt放到項目路徑下
			//創建目標
			out = new FileOutputStream("aCopy.txt");

			byte[] by = new byte[1024];
			int len = 0;
			while ((len = in.read(by)) != -1) {
				out.write(by, 0, len);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally { //釋放資源
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	//JDK1.7新特性,資源自動關閉.需要把源和目標的創建放到try語句中的一對()中
	private static void test2() {
		try (
				//創建源
				InputStream in = new FileInputStream("a.txt"); //需要先準備一個a.txt放到項目路徑下
				//創建目標
				OutputStream out = new FileOutputStream("aCopy.txt");
			) 
			{
				byte[] by = new byte[1024];
				int len = 0;
				while ((len = in.read(by)) != -1) {
					out.write(by, 0, len);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}


JDK1.7後的改變



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章