使用nio来读写文件

Java读写文件在之前都是使用outputstream那一套,是在是有点烦..

这次需要写个小功能,需要读取文件的每一行进行某个操作之后再写入到一个新文件中去,因此各种搜索之后使用了nio中对文件的一些操作,至少是美观且大方了起来,因此记录下来,防止后面再需要的时候找不到.

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
import mian.AbstractMain;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Collections;

/**
* Created by pfliu on 2019/04/28.
*/
public class NioTest extends AbstractMain {

public static void main(String[] args) {
new NioTest().parseArgsAndRun(args);
}

@Override
public void run() throws IOException {
Path source = FileSystems.getDefault().getPath("/Users/pfliu/study/test/source");
Path target = FileSystems.getDefault().getPath("/Users/pfliu/study/test/target");

Files.lines(source).forEach(per -> {
logger.info("line: {}", per);
try {
Files.write(target, Collections.singleton(per), StandardOpenOption.APPEND);
} catch (IOException e) {
e.printStackTrace();
}
});
}
}

通过上面简单的操作,就实现了对文件1的按行读取并写入文件2,当然中间可以掺杂你想要的任何操作.


完。



ChangeLog

2019-04-28 完成

以上皆为个人所思所得,如有错误欢迎评论区指正。

欢迎转载,烦请署名并保留原文链接。

联系邮箱:huyanshi2580@gmail.com

更多学习笔记见个人博客——>呼延十