FTP上传单个文件
/** FTP地址 */
private static final String GY_SERVER = "10.0.0.1";// 正式
/**** 用户名*/
private static final String GY_FTP_USERNAME = "test";// 正式
/***** 密码*/
private static final String GY_FTP_USERPASSWORD = "test";// 正式
/**** 远程FTP上传的目录*/
private static final String GY_FTP_REMOTE_PATH = "/data/ftpFile/";
String path= this.getClass().getClassLoader().getResource(".").getPath();
/** 文件名 **/
String fileName = getFileName()+".txt";
String filePath = path+"txtFile/"+fileName;
/**** 本地保存txt的目录*/
String GY_SAVE_DIR = path+"txtFile/";
File txtFile = new File(GY_SAVE_DIR);
if (!txtFile.exists()) {
txtFile.mkdir();
}
ftpUpload(GY_SAVE_DIR + File.separator + fileName, fileName);
/**
* FTP上传单个文件
*/
public static void ftpUpload(String filename, String oldFileName) {
FTPClient ftpClient = new FTPClient();
FileInputStream fis = null;
int reply;
try {
System.out.println("====================connect start============================");
ftpClient.connect(GY_SERVER);
ftpClient.setConnectTimeout(20000);
System.out.println("====================login start============================");
ftpClient.login(GY_FTP_USERNAME, GY_FTP_USERPASSWORD);
reply = ftpClient.getReplyCode();
System.out.println("======reply========" + reply);
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
System.out.println("连接服务器失败");
}
System.out.println("登陆服务器成功");
File srcFile = new File(filename);
fis = new FileInputStream(srcFile);
//设置上传目录
ftpClient.changeWorkingDirectory(GY_FTP_REMOTE_PATH);
ftpClient.setBufferSize(10240);
ftpClient.setControlEncoding("UTF-8");
//设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
//remotePath路径传输 是以.tmp格式传输到远程目录下
String remotePath = oldFileName+".tmp";
ftpClient.storeFile(remotePath, fis);
//将远程目录下的文件.tmp格式改为.txt格式,保持文件原子性
ftpClient.rename(remotePath, oldFileName);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("FTP客户端出错!", e);
} finally {
IOUtils.closeQuietly(fis);
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("关闭FTP连接发生异常!", e);
}
}
}