使用Java:
我有一个代表文件的byte[]
。
如何将其写入文件(例如:C:\myfile.pdf
)?
我知道可以使用InputStream,但我似乎无法解决它。
使用Java:
我有一个代表文件的byte[]
。
如何将其写入文件(例如:C:\myfile.pdf
)?
我知道可以使用InputStream,但我似乎无法解决它。
FileUtils.writeByteArrayToFile(new File("pathname"), myByteArray)
或者,如果您坚持要自找麻烦...
try (FileOutputStream fos = new FileOutputStream("pathname")) {
fos.write(myByteArray);
//fos.close(); There is no more need for this line since you had created the instance of "fos" inside the try. And this will automatically close the OutputStream
}
没有使用任何库:
try (FileOutputStream stream = new FileOutputStream(path)) {
stream.write(bytes);
}
使用Google Guava:
Files.write(bytes, new File(path));
FileUtils.writeByteArrayToFile(new File(path), bytes);
所有这些策略都需要你在某个时候捕获 IOException 异常。
path
的字符集是什么?FileOutputStream 文档没有提到这一点,所以这可能是特定于平台的。我猜在绝大多数情况下它是 UTF-8。
bytes
会按原样写入,不涉及字符集。 - Alexey Nezhdanov使用 java.nio.file
的另一种解决方案:
byte[] bytes = ...;
Path path = Paths.get("C:\\myfile.pdf");
Files.write(path, bytes);
C:\myfile.pdf
在安卓上无法使用...;) - TBieniek自Java 7以来,可以使用java.nio.file.Files中的一行代码:
Files.write(new File(filePath).toPath(), data);
如果数据是byte[],文件路径是String,你可以使用StandardOpenOptions类添加多个文件打开选项。请添加throws或者用try/catch包围。
Paths.get(filePath);
替代 new File(filePath).toPath()
。 - Tim Büthe从 Java 7 开始,您可以使用 try-with-resources 语句来避免资源泄漏并使代码更易于阅读。更多信息请参见这里。
要将您的byteArray
写入文件,您可以执行以下操作:
try (FileOutputStream fos = new FileOutputStream("fullPathToFile")) {
fos.write(byteArray);
} catch (IOException ioe) {
ioe.printStackTrace();
}
尝试使用OutputStream
或更具体地说是FileOutputStream
基本示例:
String fileName = "file.test";
BufferedOutputStream bs = null;
try {
FileOutputStream fs = new FileOutputStream(new File(fileName));
bs = new BufferedOutputStream(fs);
bs.write(byte_array);
bs.close();
bs = null;
} catch (Exception e) {
e.printStackTrace()
}
if (bs != null) try { bs.close(); } catch (Exception e) {}
File f = new File(fileName);
byte[] fileContent = msg.getByteSequenceContent();
Path path = Paths.get(f.getAbsolutePath());
try {
Files.write(path, fileContent);
} catch (IOException ex) {
Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);
}
////////////////////////// 1] 将文件转换为字节数组 [] ///////////////////
Path path = Paths.get(p);
byte[] data = null;
try {
data = Files.readAllBytes(path);
} catch (IOException ex) {
Logger.getLogger(Agent1.class.getName()).log(Level.SEVERE, null, ex);
}
/////////////////////// 2] 字节数组转文件 ///////////////////////////
File f = new File(fileName);
byte[] fileContent = msg.getByteSequenceContent();
Path path = Paths.get(f.getAbsolutePath());
try {
Files.write(path, fileContent);
} catch (IOException ex) {
Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);
}
try {} finally {}
。 - Steven Schlansker