与Java:

我有一个字节[],代表一个文件。

我如何写这个文件(即。C: \ myfile.pdf)

我知道它是用InputStream完成的,但我似乎无法解决它。


当前回答

同样从Java 7开始,一行Java .nio.file. files:

Files.write(new File(filePath).toPath(), data);

其中data是字节[],filePath是字符串。您还可以使用StandardOpenOptions类添加多个文件打开选项。添加投掷或环绕尝试/接。

其他回答

从Java 7开始,您可以使用try-with-resources语句来避免资源泄漏,并使您的代码更易于阅读。这里有更多。

要把你的byteArray写入一个文件,你会做:

try (FileOutputStream fos = new FileOutputStream("fullPathToFile")) {
    fos.write(byteArray);
} catch (IOException ioe) {
    ioe.printStackTrace();
}

使用java.nio.file的另一个解决方案:

byte[] bytes = ...;
Path path = Paths.get("C:\\myfile.pdf");
Files.write(path, bytes);

我知道它是用InputStream完成的

实际上,你会写入一个文件输出…

基本的例子:

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) {}

同样从Java 7开始,一行Java .nio.file. files:

Files.write(new File(filePath).toPath(), data);

其中data是字节[],filePath是字符串。您还可以使用StandardOpenOptions类添加多个文件打开选项。添加投掷或环绕尝试/接。