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;
	}


你可能感兴趣的:(java网络通信)