从 byte[] 创建一个临时的 java.io.File
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19006461/
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
Create a temporary java.io.File from byte[]
提问by Lyth
I must use an existing method that is like saveAttachment(Attachment attachment)
where Attachment
has a File attribute
.
我必须使用一个现有的方法,就像saveAttachment(Attachment attachment)
whereAttachment
有一个File attribute
.
My problem is that I'm retrieving a byte[]
and I want to save it using this method. How can I have a "local" File
just for saving ?
我的问题是我正在检索 abyte[]
并且我想使用这种方法保存它。我怎么能有一个“本地”File
只是为了保存?
Sorry if my question is dumb, I don't know much about Files in Java.
抱歉,如果我的问题很愚蠢,我对 Java 中的文件知之甚少。
采纳答案by TheKojuEffect
File tempFile = File.createTempFile(prefix, suffix, null);
FileOutputStream fos = new FileOutputStream(tempFile);
fos.write(byteArray);
Check out related docs:
查看相关文档:
回答by Kayaman
You're in luck.
你很幸运。
File.createTempFile(String prefix, String suffix)
Creates a file in the default temp directory of the OS, where it's guaranteed you can write to.
在操作系统的默认临时目录中创建一个文件,保证您可以写入。
回答by Kayaman
Reading All Bytes or Lines from a File
从文件中读取所有字节或行
Path file = ...;
byte[] fileArray;
fileArray = Files.readAllBytes(file);
Writing All Bytes or Lines to a File
将所有字节或行写入文件
Path file = ...;
byte[] buf = ...;
Files.write(file, buf);