我的文件由数组中的 json 元素组成。 (多个文件。每个文件都有 json 元素数组)
我有一个进程知道将每个 json 元素作为文件中的一行并处理它。
所以我创建了一个小程序来读取 JSON 数组,然后将元素写入另一个文件。 该实用程序的输出将是其他进程的输入。
我使用了 Java 7 NIO(和 gson)。
我尝试尽可能多地使用 Java 7 NIO。 我可以做些什么改进吗? 过滤器呢?哪种方法更好?
谢谢
public class TransformJsonsUsers {
public TransformJsonsUsers() {
}
public static void main(String[] args) throws IOException {
final Gson gson = new Gson();
Path path = Paths.get("C:\\work\\data\\resources\\files");
final Path outputDirectory = Paths
.get("C:\\work\\data\\resources\\files\\output");
DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
@Override
public boolean accept(Path entry) throws IOException {
// which is better?
// BasicFileAttributeView attView = Files.getFileAttributeView(entry, BasicFileAttributeView.class);
// return attView.readAttributes().isRegularFile();
return !Files.isDirectory(entry);
}
};
DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path, filter);
directoryStream.forEach(new Consumer<Path>() {
@Override
public void accept(Path filePath) {
String fileOutput = outputDirectory.toString() + File.separator + filePath.getFileName();
Path fileOutputPath = Paths.get(fileOutput);
try {
BufferedReader br = Files.newBufferedReader(filePath);
User[] users = gson.fromJson(br, User[].class);
BufferedWriter writer = Files.newBufferedWriter(fileOutputPath, Charset.defaultCharset());
for (User user : users) {
writer.append(gson.toJson(user));
writer.newLine();
}
writer.flush();
} catch (IOException e) {
throw new RuntimeException(filePath.toString(), e);
}
}
});
}
}
最佳答案
如果您想读取目录中的所有文件,则使用 Filter 是没有意义的。过滤器主要设计用于应用一些过滤条件并读取文件的子集。它们两者在整体性能上可能没有任何真正的差异。
如果您希望提高性能,可以尝试几种不同的方法。
多线程
根据目录中存在的文件数量以及您的 CPU 的强大程度,您可以应用多线程一次处理多个文件
排队
现在您正在同步读取和写入另一个文件。您可以使用队列对文件内容进行排队并创建异步编写器。
您也可以结合使用这两种方法来进一步提高性能。
关于java - 使用Java 7 nio读写文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27430662/