使用Java 7 nio读写文件

艾尔·戈兰(Eyal Golan)

我有包含数组中的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);
            }

        }
    });
}

}

卡穆尔

如果要从目录中读取所有文件,则没有必要使用过滤器。筛选器主要用于应用某些筛选条件并读取文件的子集。两者在整体性能上可能没有任何实际差异。

如果您想提高性能,可以尝试几种不同的方法。

多线程

根据目录中存在多少文件以及您的CPU的强大程度,您可以应用多线程来一次处理多个文件

排队

现在,您正在同步读取和写入另一个文件。您可以使用“队列”将文件的内容排队,并创建异步编写器。

您也可以将这两种方法结合起来以进一步提高性能。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章