本例以Windows, JDK1.7 为基础,这里使用FileInputStream这个类来,并使用单字节和多字节(缓存)来完成对文件的读取。
代码如下:
FileReadInputStream.java

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package com.devnp.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class FileReadInputStream {

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub

readWithBuffer2();
}

/**
* 采用单字节的读取方式
* @throws IOException
*/
public static void read() throws IOException{
File file = new File("D:\\Person-Test\\1.txt");

InputStream inputStream = new FileInputStream(file);

StringBuilder stringBuilder = new StringBuilder();

int ch ;
while ((ch = inputStream.read()) != -1) {
stringBuilder.append((char)ch);
}

inputStream.close();

System.out.println(stringBuilder);
}

/**
* 采用缓存的方的,一次性读取10个字节
* @throws IOException
*/
public static void readWithBuffer() throws IOException{
File file = new File("D:\\Person-Test\\1.txt");

InputStream inputStream = new FileInputStream(file);

StringBuilder stringBuilder = new StringBuilder();

byte [] bytes = new byte[10] ;
int n ;
while (( n = inputStream.read(bytes)) != -1) {
stringBuilder.append(new String(bytes, 0 , n));

}

inputStream.close();

System.out.println(stringBuilder);
}

/**
* 采用缓存的方的,一次性读取10个字节
* @throws IOException
*/
public static void readWithBuffer2() throws IOException{
File file = new File("D:\\Person-Test\\1.txt");

InputStream inputStream = new FileInputStream(file);

StringBuilder stringBuilder = new StringBuilder();

byte [] bytes = new byte[10] ;
int n ;
while (( n = inputStream.read(bytes, 0, bytes.length)) != -1) {
stringBuilder.append(new String(bytes, 0 , n));

}

inputStream.close();

System.out.println(stringBuilder);
}
}