1. 程式人生 > >java的輸入輸出流與檔案操作(2.讀入寫出及關流)

java的輸入輸出流與檔案操作(2.讀入寫出及關流)

1.如何讀取檔案。

可以一個位元組一個位元組的讀,也可以使用緩衝,一塊一塊資料的讀。

一般使用第二種,因為比較快。

@Test
	public void TestRead() throws IOException {
		byte buf[] = new byte[1024];
		FileInputStream fin = new FileInputStream("E:/test/io.txt");
		int len = 0;
		while((len=fin.read(buf)) != -1){
			for (int i = 0; i < len; i++) {
				System.out.print((char)buf[i]);
			}
		}
		fin.close();
	}

2.如何寫出檔案。

寫出檔案可以追加寫出,也可以重新寫出。

追加寫出就是在原來檔案的基礎上繼續追加內容。

重新寫出就是擦除原來的檔案內容,將新的內容寫出到檔案。

具體操作看程式碼。

@Test
	public void TestOut() throws IOException{
		byte buf[] = {65,66,49,48,13,10,97,98};
		// FileOutputStream fout = new FileOutputStream("E:/test/io.txt");//重新寫出方式
		FileOutputStream fout = new FileOutputStream("E:/test/io.txt",true);//追加方式
		fout.write(buf);
		fout.close();
		/* 控制檯列印:
		 * AB10
		 * ab
		 * */
	}

3.使用流之後關流的正確操作(IO異常處理的模板)
@Test
	public void TestClose() {
		byte buf[] = new byte[512];
		int len = 0;
		FileInputStream in = null;
		try {
			in = new FileInputStream("E:/test/io.txt");
			while ((len = in.read(buf)) != -1) {
				// bytes, offset, length ,charsetName
				String string = new String(buf, 0, len, "gbk");
				System.out.print(string);
			}
		} catch (FileNotFoundException e) {
			System.err.println("找不到指定檔案!");
			// e.printStackTrace();
		} catch (IOException e) {
			System.err.println("檔案讀取失敗");
			// e.printStackTrace();
		} catch (Exception e) {
			// 作為補充
			e.printStackTrace();
		} finally {
			try {
				if (in != null) {// 不能為空(反正有點的都需要防護)
					in.close();
				}
			} catch (IOException e) {
				// 到這裡情節已經很嚴重了,可能會丟失資料
				throw new RuntimeException("關流失敗",e);
			}
		}
	}