如何在 Java 中将字节数组写入文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1769776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I write a byte array to a file in Java?
提问by rover12
How to write a byte array to a file in Java?
如何在Java中将字节数组写入文件?
采纳答案by Brian Agnew
You can use IOUtils.write(byte[] data, OutputStream output)from Apache Commons IO.
可以使用IOUtils.write(字节[]数据,OutputStream的输出)从Apache的百科全书IO。
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);
回答by Michael Lloyd Lee mlk
As Sebastian Redlpoints out the most straight forward now java.nio.file.Files.write. Details for this can be found in the Reading, Writing, and Creating Files tutorial.
正如Sebastian Redl现在指出的最直接的java.nio.file.Files.write。可以在阅读、编写和创建文件教程 中找到这方面的详细信息。
Old answer: FileOutputStream.write(byte[])would be the most straight forward. What is the data you want to write?
旧答案: FileOutputStream.write(byte[])将是最直接的。你要写入的数据是什么?
The tutorials for Java IO systemmay be of some use to you.
在对Java IO系统教程可能会有一些对你有用的。
回答by Brian Agnew
Apache Commons IO Utilshas a FileUtils.writeByteArrayToFile()method. Note that if you're doing any file/IO work then the Apache Commons IO library will do a lot of work for you.
Apache Commons IO Utils有一个FileUtils.writeByteArrayToFile()方法。请注意,如果您正在执行任何文件/IO 工作,那么 Apache Commons IO 库将为您完成大量工作。
回答by JuanZe
To write a byte array to a file use the method
要将字节数组写入文件,请使用该方法
public void write(byte[] b) throws IOException
from BufferedOutputStream class.
来自 BufferedOutputStream 类。
java.io.BufferedOutputStreamimplements a buffered output stream. By setting up such an output stream, an application can write bytes to the underlying output stream without necessarily causing a call to the underlying system for each byte written.
java.io.BufferedOutputStream实现了一个缓冲输出流。通过设置这样的输出流,应用程序可以将字节写入底层输出流,而不必为写入的每个字节调用底层系统。
For your example you need something like:
对于您的示例,您需要类似的东西:
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...
回答by Kevin Bourrillion
A commenter asked "why use a third-party library for this?" The answer is that it's way too much of a pain to do it yourself. Here's an example of how to properlydo the inverse operation of reading a byte array from a file (sorry, this is just the code I had readily available, and it's not like I want the asker to actually paste and use this code anyway):
一位评论者问“为什么要为此使用第三方库?” 答案是,自己做这件事太痛苦了。这是一个如何正确执行从文件中读取字节数组的逆操作的示例(抱歉,这只是我随时可用的代码,而且我并不希望提问者实际粘贴和使用此代码):
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();
}
Everyone ought to be thoroughly appalled by what a pain that is.
每个人都应该对这种痛苦感到彻底震惊。
Use Good Libraries.I, unsurprisingly, recommend Guava's Files.write(byte[], File).
使用好的图书馆。不出所料,我推荐 Guava 的Files.write(byte[], File)。
回答by Sebastian Redl
As of Java 1.7, there's a new way: java.nio.file.Files.write
从 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 also resolves the embarrassment that Kevin describes: reading a file is now:
Java 1.7 也解决了 Kevin 描述的尴尬:现在读取文件是:
byte[] data = Files.readAllBytes(Paths.get("source-file"));
回答by slott
No need for external libs to bloat things - especially when working with Android. Here is a native solution that does the trick. This is a pice of code from an app that stores a byte array as an image 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);
}
}