0

在我的应用程序中,我使用 Files.write 和 org.jclouds.blobstore.domain.Blob.putBlob 将字节数组写入 4MB 文件。两者同时进行。第二个选项(jcloud)更快。

我很想知道是否有更快的方法将字节数组写入文件。如果我实现我的 Files.write 它会更好。

谢谢

4

2 回答 2

0

我做了两个程序。首先使用 Files.write,然后使用 FileOutputStream 创建 1000 个 4MB 的文件。Files.write 耗时 47 秒,FileOutputStream 耗时 53 秒。

public class TestFileWrite {

    public static void main(String[] args) {
        try {
            Path path = Paths.get("/home/felipe/teste.txt");
            byte[] data = Files.readAllBytes(path);

            SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD HH:mm:ss");
            System.out.println("TestFileWrite");
            System.out.println("start: " + sdf.format(new Date()));
            for (int i = 0; i < 1000; i++) {
                Files.write(Paths.get("/home/felipe/Test/testFileWrite/file" + i + ".txt"), data);
            }
            System.out.println("end: " + sdf.format(new Date()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}



public class TestOutputStream {

    public static void main(String[] args) {
        Path path = Paths.get("/home/felipe/teste.txt");
        byte[] data = null;
        try {
            data = Files.readAllBytes(path);
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD HH:mm:ss");
        System.out.println("TestOutputStream");
        System.out.println("start: " + sdf.format(new Date()));

        for (int i = 0; i < 1000; i++) {
            try (OutputStream out = new FileOutputStream("/home/felipe/Test/testOutputStream/file" + i + ".txt")) {
                out.write(data);
            } catch (IOException e) {
                e.printStackTrace();
            }
            // Files.write(Paths.get("), data);
        }
        System.out.println("end: " + sdf.format(new Date()));
    }
}
于 2015-10-05T20:26:56.893 回答
0

我查看了代码,并且(令人惊讶地)Files.write(Path, byte[], OpenOption ...)使用固定大小的 8192 字节缓冲区写入文件。(Java 7 和 Java 8 版本)

直接写应该可以得到更好的性能;例如

    byte[] bytes = ...
    try (FileOutputStream fos = new FileOutputStream(...)) {
        fos.write(bytes);
    }
于 2015-10-05T15:11:10.480 回答