forked from lihengming/java-codes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReadFile.java
More file actions
56 lines (45 loc) · 1.38 KB
/
Copy pathReadFile.java
File metadata and controls
56 lines (45 loc) · 1.38 KB
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
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
/**
* Created by 李恒名 on 2017/6/8.
*/
public class ReadFile {
public static void read(File file) {
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
while (reader.ready()) {
System.out.println(reader.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void readByNIO(File file) {
try (FileChannel channel = new FileInputStream(file).getChannel()) {
ByteBuffer buffer = ByteBuffer.allocate((int) file.length());
channel.read(buffer);
System.out.println(new String(buffer.array()));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void readByNIO2(File file) {
try {
List<String> lines = Files.readAllLines(Paths.get(file.toURI()));
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
File file = new File("README.md");
read(file);
readByNIO(file);
readByNIO2(file);
}
}