Mic*_*mlk 74
正如Sebastian Redl现在指出的最直接的java.nio.file.Files.write.有关详细信息,请参阅" 阅读,编写和创建文件"教程.
旧答案: FileOutputStream.write(byte []) 将是最直接的.你想写什么数据?
小智 38
可以使用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);
Run Code Online (Sandbox Code Playgroud)
Seb*_*edl 32
从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);
Run Code Online (Sandbox Code Playgroud)
Java 1.7还解决了Kevin描述的尴尬:现在读取文件:
byte[] data = Files.readAllBytes(Paths.get("source-file"));
Run Code Online (Sandbox Code Playgroud)
Kev*_*ion 16
一位评论者问"为什么要使用第三方图书馆?" 答案是,自己做这件事太痛苦了.下面是一个如何正确执行从文件中读取字节数组的逆操作的示例(对不起,这只是我现有的代码,并不像我希望请求者实际粘贴并使用此代码):
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();
}
Run Code Online (Sandbox Code Playgroud)
每个人都应该被痛苦所震惊.
使用好图书馆.不出所料 ,我推荐Guava的Files.write(byte [],File).
Jua*_*nZe 12
要将字节数组写入文件,请使用该方法
public void write(byte[] b) throws IOException
Run Code Online (Sandbox Code Playgroud)
来自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...
Run Code Online (Sandbox Code Playgroud)
Apache Commons IO Utils有一个FileUtils.writeByteArrayToFile()方法.请注意,如果您正在进行任何文件/ IO工作,那么Apache Commons IO库将为您完成大量工作.