从 FileOutputStream 创建文件
我正在使用 org.apache.commons.net.ftp 下载远程计算机中的文件。 有一种方法可以将文件读取到 FileOutputStream 对象。
ftpClient.retrieveFile("/" + ftpFile.getName(), fos);
问题是,我有另一种接受 File
对象的方法。因此,我需要创建一个 File
对象文件 FileOutputStream
。我认为,我需要创建一个 InputStream 才能从 FileOutputStream 创建文件对象。这是正确的吗?我可能会遗漏一些东西,应该有一种简单的方法可以从 FileOutputStream
创建 File
吗?
I'm using org.apache.commons.net.ftp
to download files in a remote machine.
There is a method, that reads the files to a FileOutputStream
object.
ftpClient.retrieveFile("/" + ftpFile.getName(), fos);
Problem, here is, i've another method that accepts a File
object. So, i need to create a File
object file the FileOutputStream
. I think, i need to create an InputStream
to be able to create a file object from the FileOutputStream
. is this correct? I might be missing something and there should be an easy way to create a File
from a FileOutputStream
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
FileOutputStream 有一个采用 File 对象的构造函数。
以下应该执行您需要执行的操作:
FileOutputStream has a constructor that takes a File object.
The following should do what you need it to do:
请注意,除了 mcfinnigan 的答案之外,您还必须知道,当您使用代码时:
然后将在您的文件系统上的第一行创建一个空文件。然后,如果第二行抛出异常,因为路径
"/" + ftpFile.getName()
不存在远程文件,则空文件仍将位于您的文件系统上。所以我用 Guava 做了一些 LazyInitOutputStream 来处理这个问题:
我在使用 Spring 集成 remote.file 包和 FTP/SFTP 文件下载功能时遇到了这个问题。我这样用它来解决这个空文件问题:
Note that in addition to the answer of mcfinnigan, you must know that when you use the code:
Then an empty file will be created on your filesystem on the first line. Then if the 2nd line throws an exception, because no remote file exist for path
"/" + ftpFile.getName()
, the empty file will still be on your filesystem.So I've done a little LazyInitOutputStream with Guava to handle that:
I've encoutered this problem while using Spring integration remote.file packages, with the FTP/SFTP file download features. I use it like that to solve this empty file problem: