如何用 Java 将字节数组写入文件?

如何在 Java 中将字节数组写入文件?

149382 次浏览

正如 塞巴斯蒂安 · 雷德尔指出的最直接的现在 Files.write。这方面的细节可以在 读取、写入和创建文件教程中找到。


老答案: Write (byte []) 将是最直接的?

Java IO 系统教程可能对你有用。

Apache Commons IO Utils 有一个 WriteByteArrayToFile ()方法。请注意,如果您正在执行任何文件/IO 工作,那么 Apache Commons IO 库将为您执行大量工作。

您可以从 Apache Commons IO使用 Write (byte [] data,OutputStream 输出)

KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
SecretKey key = kgen.generateKey();
byte[] encoded = key.getEncoded();
FileOutputStream output = new FileOutputStream(new File("target-file"));
IOUtils.write(encoded, output);

使用该方法将字节数组写入文件

public void write(byte[] b) throws IOException

来自 BufferedOutputStream 类。

Java.io.BufferedOutputStream 实现了一个缓冲的输出流。通过设置这样的输出流,应用程序可以将字节写入底层输出流,而不必为写入的每个字节调用底层系统。

对于你的例子,你需要这样的东西:

String filename= "C:/SO/SOBufferedOutputStreamAnswer";
BufferedOutputStream bos = null;
try {
//create an object of FileOutputStream
FileOutputStream fos = new FileOutputStream(new File(filename));


//create an object of BufferedOutputStream
bos = new BufferedOutputStream(fos);


KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
SecretKey key = kgen.generateKey();
byte[] encoded = key.getEncoded();


bos.write(encoded);


}
// catch and handle exceptions...

一位评论者问道: “为什么要使用第三方库呢?”答案是自己动手太痛苦了。下面是一个 适当地如何从文件中读取字节数组的反向操作的例子(对不起,这只是我随时可用的代码,并不是我想让请求者实际粘贴并使用这些代码) :

public static byte[] toByteArray(File file) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean threw = true;
InputStream in = new FileInputStream(file);
try {
byte[] buf = new byte[BUF_SIZE];
long total = 0;
while (true) {
int r = in.read(buf);
if (r == -1) {
break;
}
out.write(buf, 0, r);
}
threw = false;
} finally {
try {
in.close();
} catch (IOException e) {
if (threw) {
log.warn("IOException thrown while closing", e);
} else {
throw e;
}
}
}
return out.toByteArray();
}

每个人都应该被这种痛苦彻底震惊。

使用好的图书馆。毫无疑问,我推荐番石榴的 Write (byte [] ,File)

在 Java 1.7中,有一种新的方法: java.nio.file.Files.write

import java.nio.file.Files;
import java.nio.file.Paths;


KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
SecretKey key = kgen.generateKey();
byte[] encoded = key.getEncoded();
Files.write(Paths.get("target-file"), encoded);

Java 1.7也解决了 Kevin 描述的尴尬: 读取文件现在是:

byte[] data = Files.readAllBytes(Paths.get("source-file"));

不需要外部库来膨胀东西——特别是在使用 Android 时。这里有一个本地解决方案,可以解决这个问题。这是一段来自应用程序的代码,该应用程序将字节数组存储为图像文件。

    // Byte array with image data.
final byte[] imageData = params[0];


// Write bytes to tmp file.
final File tmpImageFile = new File(ApplicationContext.getInstance().getCacheDir(), "scan.jpg");
FileOutputStream tmpOutputStream = null;
try {
tmpOutputStream = new FileOutputStream(tmpImageFile);
tmpOutputStream.write(imageData);
Log.d(TAG, "File successfully written to tmp file");
}
catch (FileNotFoundException e) {
Log.e(TAG, "FileNotFoundException: " + e);
return null;
}
catch (IOException e) {
Log.e(TAG, "IOException: " + e);
return null;
}
finally {
if(tmpOutputStream != null)
try {
tmpOutputStream.close();
} catch (IOException e) {
Log.e(TAG, "IOException: " + e);
}
}
         File file = ...
byte[] data = ...
try{
FileOutputStream fos = FileOutputStream(file);
fos.write(data);
fos.flush();
fos.close();
}catch(Exception e){
}

但是如果字节数组长度大于1024,则应该使用循环来写入数据。