1. 程式人生 > >檔案位元組流FileInputStream,FileOutputStream

檔案位元組流FileInputStream,FileOutputStream

1.從檔案讀取資訊到記憶體(位元組)

        File f = new File("/Users/hh/Desktop/test豆腐缶122.txt");
		//因為file沒有讀寫的能力,所以需要FileInputStream
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(f);
			//定義一個位元組陣列,相當於快取
			byte []bytes = new byte[1024];
			int n = 0;//得到實際讀取到的位元組數
			//迴圈讀取
			while ((n = fis.read(bytes))!= -1) {
				//把位元組轉成string
				String s = new String(bytes,0,n);
				System.out.println(s);
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			//關閉檔案流必須放在這裡
			try {
				fis.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

2.從記憶體讀取資訊到檔案

            File f =  new File("/Users/hh/Desktop/test11.txt");
		//位元組輸出流
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(f);
			String s = "林玉,女,漢族,育有一女,可可。\r\n";
			String s1 = "吳曉龍是個胖子";
			byte []b = new byte[1024];//剛好1k;
			//如何把String轉化成Bytes陣列
			byte []bytes = s.getBytes();
			fos.write(bytes);
			fos.write(s1.getBytes());
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
			try {
				fos.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}

3.位元組流有兩種建立方式

(1)先建立檔案,在生成位元組流

File f =  new File("/Users/hh/Desktop/test11.txt");
FileOutputStream fos = new FileOutputStream(f);

(2)直接建立位元組流

FileInputStream fis = new FileInputStream("/Users/hh/Desktop/img-180207150924.jpg");

4.圖片拷貝

                //思路 先把圖片讀入到記憶體--》寫入到某個檔案
		//因為是二進位制檔案,所以只能用位元組流完成
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream("/Users/hh/Desktop/img-180207150924.jpg");
			fos = new FileOutputStream("/Users/hh/Desktop/臨時版本/營業執照掃描件.jpg");
			byte []bytes = new byte[1024];
			int n = 0;//記錄實際讀取到的位元組數
			//迴圈讀取
			while ((n=fis.read(bytes))!=-1) {
				//輸出到制定檔案
				fos.write(bytes);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				fis.close();
				fos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}