注意,除了mcfinnigan的答案,你必須知道,當您使用代碼:
FileOutputStream fos = new FileOutputStream(f); // create a file output stream around f
ftpClient.retrieveFile("/" + ftpFile.getName(), fos);
然後一個空文件將在第一行的文件系統上創建。然後,如果第二行引發異常,因爲路徑"/" + ftpFile.getName()
上沒有遠程文件,則空文件仍將位於文件系統中。
所以我做了一些LazyInitOutputStream與番石榴來處理:
public class LazyInitOutputStream extends OutputStream {
private final Supplier<OutputStream> lazyInitOutputStreamSupplier;
public LazyInitOutputStream(Supplier<OutputStream> outputStreamSupplier) {
this.lazyInitOutputStreamSupplier = Suppliers.memoize(outputStreamSupplier);
}
@Override
public void write(int b) throws IOException {
lazyInitOutputStreamSupplier.get().write(b);
}
@Override
public void write(byte b[]) throws IOException {
lazyInitOutputStreamSupplier.get().write(b);
}
@Override
public void write(byte b[], int off, int len) throws IOException {
lazyInitOutputStreamSupplier.get().write(b,off,len);
}
public static LazyInitOutputStream lazyFileOutputStream(final File file) {
return lazyFileOutputStream(file,false);
}
public static LazyInitOutputStream lazyFileOutputStream(final File file,final boolean append) {
return new LazyInitOutputStream(new Supplier<OutputStream>() {
@Override
public OutputStream get() {
try {
return new FileOutputStream(file,append);
} catch (FileNotFoundException e) {
throw Throwables.propagate(e);
}
}
});
}
同時使用Spring集成remote.file包,與FTP/SFTP文件下載功能,我encoutered這個問題。我用它來解決這個空文件問題:
try (OutputStream downloadedFileStream = LazyInitOutputStream.lazyFileOutputStream(destinationfilePath.toFile())) {
remoteFileSession.read(source, downloadedFileStream);
}
不應該retrieveFile創建InputStream?不應該是您用來創建FileOutputStream的文件嗎?請問 – 2012-01-04 12:12:48
,意思是:「我需要創建一個File對象文件FileOutputStream」? – Gangnus 2012-01-04 12:26:29
@Peter Lawrey - retrieveFile通過FTP讀取文件並將文件的內容寫入OutPutStream – user957183 2012-01-04 12:31:19