有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将字节数组写入文件的快速方法

在我的应用程序中,我使用文件。编写并组织。jclouds。布洛斯托。领域斑点。putBlob将字节数组写入4MB文件。两者同时进行。第二个选项(jcloud)更快

我想知道是否有一种更快的方法在文件中写入字节数组。如果我实现我的文件。写它更好

谢谢


共 (2) 个答案

  1. # 1 楼答案

    我做了两个节目。首先使用文件。使用FileOutputStream进行写入和第二次写入,以创建1000个4MB的文件。文件夹。写入耗时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()));
        }
    }
    
  2. # 2 楼答案

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

    您应该能够通过直接编写来获得更好的性能;e、 g

        byte[] bytes = ...
        try (FileOutputStream fos = new FileOutputStream(...)) {
            fos.write(bytes);
        }