/
BigFileReadWrite.java
105 lines (98 loc) · 2.77 KB
/
BigFileReadWrite.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package com.critc;
import java.io.*;
import java.util.Scanner;
/**
* Created by 孔垂云 on 2017/6/1.
*/
public class BigFileReadWrite {
/**
* 读取大文件
*
* @param filePath
*/
public void readFile(String filePath) {
FileInputStream inputStream = null;
Scanner sc = null;
try {
inputStream = new FileInputStream(filePath);
sc = new Scanner(inputStream, "UTF-8");
while (sc.hasNextLine()) {
String line = sc.nextLine();
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (sc != null) {
sc.close();
}
}
}
/**
* 读取文件
*
* @param filePath
*/
public void readFile2(String filePath) {
File file = new File(filePath);
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file), 5 * 1024 * 1024); //如果是读大文件,设置缓存
String tempString = null;
while ((tempString = reader.readLine()) != null) {
System.out.println(tempString);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 写文件
* @param filePath
* @param fileContent
*/
public void writeFile(String filePath, String fileContent) {
File file = new File(filePath);
// if file doesnt exists, then create it
FileWriter fw = null;
try {
if (!file.exists()) {
file.createNewFile();
}
fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(fileContent);
bw.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
BigFileReadWrite file = new BigFileReadWrite();
//file.readFile("D:\\test.txt");
// file.readFile2("D:\\test.txt");
file.writeFile("D:\\test2.txt", "测试写入");
}
}