问题遇到的现象和发生背景
安卓下载ftp服务器中的jpg图片,下完完成之后,保存在图片中的数据丢失了一部分
问题相关代码,请勿粘贴截图
//ftp连接代码
public FTPClient getFTPClient(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword) {
if (ftpClient == null) {
ftpClient = new FTPClient();
}
if (ftpClient.isConnected()) {
return ftpClient;
}
Log.e(TAG, "ftpHost:" + ftpHost + ",ftpPort:" + ftpPort);
try {
// 设置超时时间
ftpClient.setConnectTimeout(50000);
// 设置中文编码集,防止中文乱码
ftpClient.setControlEncoding("GBK");
//连接服务器
ftpClient.connect(ftpHost, ftpPort);
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
Log.e(TAG, "connect fail: replyCode:" + replyCode);
return ftpClient;
}
Log.e(TAG, "connect success: replyCode" + replyCode);
//登录
Log.e(TAG, "ftpUserName:" + ftpUserName + ",ftpPassword:" + ftpPassword);
ftpClient.login(ftpUserName, ftpPassword);
int replyCode1 = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode1)) {
ftpClient.disconnect();
Log.e(TAG, "login fail: replyCode:" + replyCode1);
return ftpClient;
}
Log.e(TAG, "login success: replyCode:" + replyCode);
//使用被动模式
ftpClient.enterLocalPassiveMode();
//二进制文件支持
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, e.getMessage());
return null;
}
return ftpClient;
}
//文件下载代码
private void downLoadFile(String name){
//下载文件
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
// 默认失败
boolean flag = false;
try {
//使用被动模式
ftpClient.enterLocalPassiveMode();
// 跳转到文件目录
ftpClient.changeWorkingDirectory(ftpFileNow);
// 获取目录下文件集合
FTPFile[] files = ftpClient.listFiles();
for (FTPFile file : files) {
// 取得指定文件并下载
if (file.getName().equals(name)) {
Log.e("fileName:", name);
File downFile = new File(createNew.getPath() + File.separator + file.getName());
if (downFile.exists()){
downFile.delete();
downFile.createNewFile();
}
OutputStream fos = null;
try {
fos = new FileOutputStream(downFile);
flag = ftpClient.retrieveFile(new String(file.getName().getBytes(),StandardCharsets.ISO_8859_1), fos);
fos.flush();
if (flag){
showToast("下载成功");
downLoadFilePath = createNew.getPath();
}else {
showToast("下载失败");
}
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}