Java 中的 byte[] 到文件
对于 Java:
我有一个代表文件的 byte[]
。
我如何将其写入文件(即C:\myfile.pdf
)
我知道它是用InputStream完成的,但我似乎无法解决它。
With Java:
I have a byte[]
that represents a file.
How do I write this to a file (ie. C:\myfile.pdf
)
I know it's done with InputStream, but I can't seem to work it out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(12)
使用 Apache Commons IO
或者,如果您坚持为自己工作......
Use Apache Commons IO
Or, if you insist on making work for yourself...
没有任何库:
使用Google Guava:
使用 Apache Commons:
所有这些策略都要求您在某个时刻捕获 IOException。
Without any libraries:
With Google Guava:
With Apache Commons:
All of these strategies require that you catch an IOException at some point too.
使用 java.nio.file 的另一个解决方案:
Another solution using
java.nio.file
:同样从 Java 7 开始,一行 java.nio.file.Files:
其中 data 是您的 byte[],filePath 是一个字符串。您还可以使用 StandardOpenOptions 类添加多个文件打开选项。添加 throws 或用 try/catch 包围。
Also since Java 7, one line with java.nio.file.Files:
Where data is your byte[] and filePath is a String. You can also add multiple file open options with the StandardOpenOptions class. Add throws or surround with try/catch.
从Java 7开始,您可以使用try-with-resources语句来避免资源泄漏并使代码更易于阅读。更多信息请参见此处。
要将您的
byteArray
写入文件,您可以执行以下操作:From Java 7 onward you can use the try-with-resources statement to avoid leaking resources and make your code easier to read. More on that here.
To write your
byteArray
to a file you would do:尝试使用
OutputStream
或更具体地说FileOutputStream
Try an
OutputStream
or more specificallyFileOutputStream
基本示例:
Basic example:
/////////////////////////// 1] 文件到字节 [] /////////////////// //
///////////////////////// 2] 字节 [] 到文件 //////////////////// /////////////////
////////////////////////// 1] File to Byte [] ///////////////////
/////////////////////// 2] Byte [] to File ///////////////////////////
的实际上,你会写入到 文件输出...
Actually, you'd be writing to a file output...
在这个程序中,我们使用字符串生成器读取和打印字节偏移量和长度数组,并将字节偏移量长度写入新文件。
`在此处输入代码
控制台中的 O/P : fghij
新文件中的 O/P :cdefg
This is a program where we are reading and printing array of bytes offset and length using String Builder and Writing the array of bytes offset length to the new file.
`Enter code here
O/P in console : fghij
O/P in new file :cdefg
您可以尝试 Cactoos:
更多详细信息:http://www.yegor256.com/2017/06/22/object-orient-input-output- in-cactoos.html
You can try Cactoos:
More details: http://www.yegor256.com/2017/06/22/object-oriented-input-output-in-cactoos.html