Java IO读写文件原创
# 1. 依赖
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons.lang3.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons.io.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>${commons.compress.version}</version>
</dependency>
</dependencies>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 2. InputStream
private static void readExecuteData(File inputFile) throws IOException {
//读gz压缩文件
GzipCompressorInputStream inputStream = new GzipCompressorInputStream(new FileInputStream(inputFile));
//读普通文件
//BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(inputFile));
try (LineIterator iterator = IOUtils.lineIterator(inputStream, StandardCharsets.UTF_8)) {
while (iterator.hasNext()) {
String line = iterator.nextLine();
System.out.println(line);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 2. OutputStream
# 2.1.
static Map<String, OutputStream> outputStreamMap = new ConcurrentHashMap<>();
private synchronized void write(String path, String filePath, List<String> records, HashMap<String, Long> outputRowRecord, HashMap<String, Long> outputSizeRecord) throws Exception {
IOUtils.writeLines(records, null, this.getOutputStream(filePath), StandardCharsets.UTF_8);
}
private OutputStream getOutputStream(String path) throws Exception {
OutputStream outputStream;
if (!outputStreamMap.containsKey(path)) {
outputStream = new BufferedOutputStream(FileUtils.openOutputStream(new File(path), true));
outputStreamMap.put(path, outputStream);
} else {
outputStream = outputStreamMap.get(path);
}
return outputStream;
}
public void closeOutputStreams() {
outputStreamMap.forEach((path, outputStream) -> {
try {
outputStream.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
});
}
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
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
- 02
- 2025-03-28拍婚纱照 原创04-02
- 03
- 2024-04-05的晚上 原创04-01