1 /**
2 * 字节流:字符流只能处理字符,对于图片等字节文件
3 */
4 @Test
5 public void test() {
6 //inputStream
7 FileInputStream fileInputStream= null;
8 try {
9 File file=new File("hello.txt");
10 fileInputStream = new FileInputStream(file);
11 byte[]bytes=new byte[5];
12 int len;
13 while ((len=fileInputStream.read(bytes))!=-1){
14 String str=new String(bytes,0,len);
15 System.out.println(str);
16 }
17 } catch (IOException e) {
18 e.printStackTrace();
19 } finally {
20 try {
21 fileInputStream.close();
22 } catch (IOException e) {
23 e.printStackTrace();
24 }
25 }
26
27 }
28 //jpg图像非文本文件,使用字节流可以进行复制
29
30 @Test
31 public void test2(){
32 FileInputStream fileInputStream= null;
33 FileOutputStream fileOutputStream= null;
34 try {
35 File file=new File("123.jpg");
36 File file2=new File("1234.jpg");
37 fileInputStream = new FileInputStream(file);
38 fileOutputStream = new FileOutputStream(file2);
39 byte[]bytes=new byte[5];
40 int len;
41 while ((len=fileInputStream.read(bytes))!=-1){
42 fileOutputStream.write(bytes,0,len);
43 }
44 } catch (IOException e) {
45 e.printStackTrace();
46 } finally {
47 try {
48 fileInputStream.close();
49 } catch (IOException e) {
50 e.printStackTrace();
51 }
52 try {
53 fileOutputStream.close();
54 } catch (IOException e) {
55 e.printStackTrace();
56 }
57 }
58 }
59 }