如何在Java中将字节数组写入文件?
发布于 2009-11-20 19:14:31
您可以从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);
发布于 2013-07-17 02:33:32
从Java1.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"));
发布于 2009-11-20 19:17:44
要将字节数组写入文件,请使用方法
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...
https://stackoverflow.com/questions/1769776
复制相似问题