linux下用java实现ftp上传、下载文件

//1、依赖的jar包:commons-net-1.4.1.jar

/**
	 * 上传文件到ftp服务器
	 * @param ftpHost
	 * @param userName
	 * @param passWord
	 * @param port
	 * @param ftpPath
	 * @param fileContent
	 * @param writeTempFielPath
	 */
	public static void upLoadFileForFtp(String ftpHost, String userName,
		String passWord, int port, String writeTempFielPath, String fileContent,
		String ftpUploadPath, String ftpFileName){
		FTPClient ftpClient = null;
        try {  
        	ftpClient = initFtpClient(ftpHost, userName, passWord, port);
        	//不存在则创建 
        	newFolder(writeTempFielPath);
            boolean writeResult = saveFile(writeTempFielPath + ftpFileName, fileContent);  
            if (writeResult) {  
                File f = new File(writeTempFielPath + "/" + ftpFileName);  
                InputStream in = new FileInputStream(f);
                ftpClient.changeWorkingDirectory(ftpUploadPath);
                if (ftpClient.storeFile(ftpFileName, in)){
                	logger.info("文件" + ftpFileName + "上传成功!");
                }else{
                	logger.info("文件" + ftpFileName + "上传失败!");
                }
                in.close();  
                f.delete();  
            } else { 
            	logger.info("临时文件创建失败!");
            }  
        } catch (Exception e) {  
        	StaticVar.printExceptionInfo(logger, e);
            e.printStackTrace();  
        }finally{  
          closeConn(ftpClient); 
        }  
	}


/**
	 * 下载最新文件
	 * @param ftpHost
	 * @param userName
	 * @param passWord
	 * @param port
	 * @param ftpPath
	 * @param fileName
	 * @return
	 * @throws IOException 
	 */
	public static synchronized int downFilesForFtp(String ftpHost, String userName,
			String passWord, int port, String ftpPath) throws IOException{
		int updateCount = 0;
		OutputStream os = null;
		FTPClient ftpClient = null;
		try {
			ftpClient = initFtpClient(ftpHost, userName, passWord, port);
			ftpClient.changeWorkingDirectory(ftpPath);
			System.out.println("切换目录:"+ftpClient.getReplyString());
			FTPFile[] files = ftpClient.listFiles();
			//创建临时目录
			FileUtil.newFolder(StaticVar.TEMP_PATH);
			for (int i = 0; i < files.length; i++) {
				String fileName = files[i].getName();
				//判断文件类型
				if (fileName.indexOf(".txt") < 0){
					continue;
				}
				//判断日志文件是否已存在,没有则创建
				String downLogPath =  StaticVar.DOWN_LOG_PATH+StaticVar.DOWN_LOG_NAME;
				File downLog = new File(downLogPath);
				if (downLog.exists()){
					//判断是否已经下载过
					if (isDown(files[i], downLogPath)){
						logger.info("文件:"+fileName+"已经下载过了!");
						continue;
					}else{
						updateCount++;
					}
				}else{
					downLog.createNewFile();
					updateCount++;
				}
				String saveFilePath = StaticVar.TEMP_PATH + fileName;
				os = new FileOutputStream(new File(saveFilePath));
				boolean isDown = ftpClient.retrieveFile(fileName, os);
				//记录下载日志
				if (isDown){
					logger.info("文件:" +saveFilePath+ "下载成功!");
					FileUtil.newFolder(StaticVar.DOWN_LOG_PATH);
					String log = files[i].getName() + "&" + files[i].getSize() + "&" + DateUtil.getNowDate(DateUtil.yyyyMMddHHmmss);
					FileUtil.writeFile(downLogPath, log);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("文件列表获取失败!");
			StaticVar.printExceptionInfo(logger, e);
		}finally{
			if (null != os){
				os.flush();
				os.close();
			}
			closeConn(ftpClient);
		}
		return updateCount;
	}

/**
	 * 读取文件
	 * @param file
	 * @return
	 * @throws IOException 
	 */
	public static synchronized String readFile(String filePath) throws IOException{
		StringBuffer resultBuffer = null;
		InputStream in = null;
		BufferedReader reader = null;
		try {
			in = new FileInputStream(filePath);
			if (null != in){
				reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
				resultBuffer = new StringBuffer();  
				String data = null;
				while((data = reader.readLine()) != null){
					resultBuffer.append(data + "\n");
				}
				return resultBuffer.toString();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if (null != reader){
				reader.close();
			}
			if (null != in){
				in.close();
			}
		}
		return null;
	}



/**
	 * 写文件
	 * @param fileName
	 * @param fileContext
	 * @param writeTempFielPath
	 * @return
	 */
	public static boolean saveFile(String filePath, String fileContext) {
		try {
			File file = new File(filePath);
			if (!file.exists()) {
				if (!file.createNewFile()) {
					logger.info("文件创建失败!");
				}
			}
			BufferedWriter write = new BufferedWriter(new FileWriter(file, true));
			write.write(fileContext);
			write.flush();
			write.close();
			return true;
		} catch (Exception e) {
			logger.error("文件写入失败!");
			e.printStackTrace();
			return false;
		}
	}
	
	/**
	 * 判断文件是否已经下载
	 * @param ftpFile
	 * @param fileName
	 * @param downLogPath
	 * @return
	 * @throws IOException 
	 */
	private static boolean isDown(FTPFile ftpFile, String downLogPath) throws IOException {
		String fileName = ftpFile.getName();
		String logTxt = FileUtil.readFile(downLogPath);
		String[] logs = logTxt.split("\n");
		boolean isDown = false;
		for (String str : logs) {
			String[] log =  str.split("&");	//log[0]:文件名,log[1]:大小 (byte)
			if (fileName.equals(log[0]) && ftpFile.getSize() == Long.parseLong(log[1])){
				isDown = true;
				break;
			}
		}
		return isDown;
	}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Linux上使用Java程序上传文件FTP服务器,您可以使用Apache Commons Net库进行FTP操作。以下是一个简单的Java代码示例,用于将本地文件上传FTP服务器: ```java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; public class FTPUploader { public static void main(String[] args) throws IOException { String server = "ftp.example.com"; int port = 21; String user = "ftpuser"; String pass = "ftppass"; FTPClient ftpClient = new FTPClient(); ftpClient.connect(server, port); int replyCode = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { ftpClient.disconnect(); System.err.println("FTP server refused connection."); System.exit(1); } ftpClient.login(user, pass); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); String localFile = "/path/to/local/file"; String remoteFile = "remote_file_name"; FileInputStream inputStream = new FileInputStream(new File(localFile)); boolean uploaded = ftpClient.storeFile(remoteFile, inputStream); inputStream.close(); if (uploaded) { System.out.println("Upload successful!"); } else { System.out.println("Upload failed!"); } ftpClient.logout(); ftpClient.disconnect(); } } ``` 在上面的代码中,您需要替换变量server,port,user和pass为您的FTP服务器的详细信息,然后指定本地文件路径和远程文件名以上传文件。 希望这些信息对您有所帮助。如果您还有其他问题,请随时问我。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值