【发布时间】:2010-12-18 16:37:45
【问题描述】:
如何在Java中将字节数组写入文件?
【问题讨论】:
-
你能放一些代码并显示你想要写入文件的具体内容吗?
标签: java
如何在Java中将字节数组写入文件?
【问题讨论】:
标签: java
正如Sebastian Redl 指出的最直接的现在java.nio.file.Files.write。这方面的详细信息可以在Reading, Writing, and Creating Files tutorial 中找到。
旧答案: FileOutputStream.write(byte[]) 将是最直接的。你要写什么数据?
tutorials for Java IO system 可能对您有用。
【讨论】:
您可以从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()。谢谢塞巴斯蒂安!
一位评论者问“为什么要为此使用第三方库?”答案是自己做太痛苦了。这是一个如何正确执行从文件中读取字节数组的逆操作的示例(对不起,这只是我随时可用的代码,并不是我希望提问者实际粘贴并使用此代码):
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,则应使用循环写入数据。
【讨论】: