[英]Fast way to write a byte array into a file
在我的應用程序上,我使用Files.write和org.jclouds.blobstore.domain.Blob.putBlob將字節數組寫入4MB文件。 兩者以並發方式進行。 第二個選項(jcloud)更快。
我很想知道是否有更快的方法將字節數組寫入文件。 如果我實現我的Files.write更好。
謝謝
我看了一下代碼,(令人驚訝的是) Files.write(Path, byte[], OpenOption ...)
使用8192字節的固定大小的緩沖區寫入文件。 (Java 7和Java 8版本)
您應該可以通過直接執行寫入來獲得更好的性能。 例如
byte[] bytes = ...
try (FileOutputStream fos = new FileOutputStream(...)) {
fos.write(bytes);
}
我做了兩個程序。 首先使用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()));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.