案例1:
演示FileInputStream類的使用(用FileInputStream的對(duì)象把文件讀入到內(nèi)存)
首先要在E盤新建一個(gè)文本文件,命名為test.txt,輸入若干字符
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
public class Demo_2 { public static void main(String[] args) { File f= new File( "e:\\test.txt" ); //得到一個(gè)文件對(duì)象f,指向e:\\test.txt FileInputStream fis= null ; try { fis= new FileInputStream(f); //因?yàn)镕ile沒有讀寫的能力,所以需要使用FileInputStream byte []bytes= new byte [ 1024 ]; //定義一個(gè)字節(jié)數(shù)組,相當(dāng)于緩存 int n= 0 ; //得到實(shí)際讀取到的字節(jié)數(shù) while ((n=fis.read(bytes))!=- 1 ){ //循環(huán)讀取 String s= new String(bytes, 0 ,n); //把字節(jié)轉(zhuǎn)成String System.out.println(s); } e.printStackTrace(); } finally { //關(guān)閉文件流必須放在這里 try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } |
運(yùn)行程序,控制臺(tái)輸出test.txt中輸入的字符。
案例2:
演示FileOutputStream的使用(把輸入的字符串保存到文件中)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
public class Demo_3 { public static void main(String[] args) { File f= new File( "e:\\ss.txt" ); FileOutputStream fos= null ; //字節(jié)輸出流 try { fos= new FileOutputStream(f); String s= "你好,瘋子!\r\n" ; //\r\n為了實(shí)現(xiàn)換行保存 String s2= "24個(gè)比利" ; fos.write(s.getBytes()); fos.write(s2.getBytes()); } catch (Exception e) { e.printStackTrace(); } finally { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } } |
打開E盤名為ss.txt的文本文檔,存在輸入的字符。
案例3:圖片拷貝
首先在E盤準(zhǔn)備一張圖片,命名為a.jpg
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
public class Demo_4 { public static void main(String[] args) { //思路 先把圖片讀入到內(nèi)存,再寫入到某個(gè)文件 //因?yàn)閳D片是二進(jìn)制文件,只能用字節(jié)流完成 FileInputStream fis= null ; //輸入流 FileOutputStream fos= null ; //輸出流 try { fis= new FileInputStream( "e:\\a.jpg" ); fos= new FileOutputStream( "d:\\a.jpg" ); byte []bytes= new byte [ 1024 ]; int n= 0 ; //記錄實(shí)際讀取到的字節(jié)數(shù) while ((n=fis.read(bytes))!=- 1 ){ //read函數(shù)返回讀入緩沖區(qū)的字節(jié)總數(shù) fos.write(bytes); //輸出到指定文件 } } catch (Exception e) { e.printStackTrace(); } finally { try { fis.close(); fos.close(); } catch (Exception e) { e.printStackTrace(); } } } } |
打開D盤,點(diǎn)擊a.jpg,圖片正常顯示即運(yùn)行成功。
以上這篇Java文件(io)編程_文件字節(jié)流的使用方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://www.cnblogs.com/cxq1126/archive/2017/08/10/7341453.html