如何在Java中将字节数组写入文件?
正如Sebastian Redl所指出的,现在最直接的方法是使用java.nio.file.Files.write。详细信息可以在读写和创建文件教程中找到。
旧的回答:
FileOutputStream.write(byte[]) 是最简单直接的方法。你想要写入什么数据?
对于Java IO系统,tutorials for Java IO system 可能会有所帮助。
FileOutputStream
在Android中可行,而java.nio.file
不存在。 - Brent Faust你可以使用Apache Commons IO中的IOUtils.write(byte[] data, OutputStream output)方法。
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);
从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"));
SecretKey
相关的所有内容都不需要,只需调用 Files.write()
。感谢 Sebastian! - barfuin一位评论者问道:“为什么要使用第三方库来完成这个任务?”答案是自己动手实现太麻烦了。下面是一个例子,展示如何正确地执行从文件中读取字节数组的逆操作(抱歉,这只是我现成可用的代码,而且我也不希望提问者真的复制和使用这段代码):
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();
}
每个人都应该对这是多么痛苦感到非常震惊。
使用好的库。我毫不意外地推荐Guava的Files.write(byte[], File)。
要将字节数组写入文件,请使用以下方法:
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...
Apache Commons IO Utils提供了一个FileUtils.writeByteArrayToFile()方法。请注意,如果您正在进行任何文件/IO工作,则Apache Commons IO库将为您完成大部分工作。
不需要使用外部库来使事情变得臃肿 - 特别是在处理 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,您应该使用循环来写入数据。