I'm trying to transfer a file from my Java application to an FTP server the program works, the file is transferred, but when I go to open in the FTO folder, the file is corrupted, I think that packets are lost dur开发者_StackOverflow社区ing the file transfer. Why? And how can I fix this?
Another question, how can I stop the while
if I want to stop the file upload?
Thanks everybody!
The code inside my class:
FTPClient client = new FTPClient();
InputStream is = null;
//...
try{
client.connect(MY_FTP_URL);
client.login(USER, PASS);
InputStream is = new FileInputStream(file_path);
OutputStream os = client.storeFileStream(file_name);
byte[] buffer = new byte[1024];
int len;
//I use this way to check the transfer progress
while((len = is.read(buffer)) != -1){
os.write(buffer, 0, len);
os.flush();
}
os.close();
} catch (IOException e){
e.printStackTrace();
} finally{
try{
if(is != null){
is.close();
}
client.disconnect();
} catch(IOException e){
e.printStackTrace();
}
}
Check out the FAQ:
Q: Why are my files corrupt after transfer?
A: The most common cause for this is when the file is transfered as ASCII but the contents of the file are not ASCII and the file should be transferred as BINARY. RFC 959 says the default transfer mode should be ASCII. FTPClient conforms to the standard. You must explicitly call setFileType(FTP.BINARY_FILE_TYPE); to request binary transfer mode after logging in to the FTP server.
Call setFileType(FTP.BINARY_FILE_TYPE);
FTP has two modes ASCII (typically the default) and binary. If you are transferring anything other then text you must set the client into binary mode.
How to set the mode varies on the FTP client implementation, but for Commons IO see http://commons.apache.org/net/api/org/apache/commons/net/ftp/FTPClient.html#setFileType(int)
精彩评论