【java swing 编程】文件替换小秘书(六)

工具中服务器以及文件路径的配置信息保存,文件的上传服务器以及下载至本地实现代码如下:

package util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Properties;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

import panel.FTPServerPanel;
import panel.FilePathPanel;
import panel.PathPanel;

public class CommonUtil {
	
	public static String getToday(String theFormat){	
		SimpleDateFormat formatter = new SimpleDateFormat(theFormat,Locale.CHINESE);
		Date thedate=new Date();
		return formatter.format(thedate);
	}

	public static Icon getImg(String path) {
		return new ImageIcon(path);
	}
	
	public static void showMsgWin(String msg, int flg) {
		if(flg == 0) {
			JOptionPane.showMessageDialog(null, msg, "错误:", flg);
		} else if(flg == 1) {
			JOptionPane.showMessageDialog(null, msg, "提示:", flg);
		} else if(flg == 2) {
			JOptionPane.showMessageDialog(null, msg, "警告:", flg);
		}
	}
	
	public static String log(String flag, String msg) {
		return "    "+getToday("yyyy-MM-dd HH:mm:ss")+" ["+flag+"] >> "+msg+"\n";
	}
	
	public static void removePathPanelForFile(PathPanel pathPanel, File[] files) {
		if(files != null && files.length > 0) {
			for(File file : files) {
				if(file.exists() && file.getName().startsWith(pathPanel.getIndex())) {
					file.delete();
				}
			}
		}
	}
	
	public static File[] getPathFiles() {
		File file = new File(getRootPath(CommonUtil.class, "CommonUtil.class")+File.separatorChar+"cache/path");
		if(file != null && file.exists()) {
			return file.listFiles();
		}
		return null;
	}
	
	public static boolean downLoadFile(StringBuffer msg, FTPServerPanel serverPanel, List<PathPanel> pathList) {
		FTPToServer ftpToServer = new FTPToServer();
		boolean success = ftpToServer.connect(msg, 
				serverPanel.getHostName1().getText()+"."
						+serverPanel.getHostName2().getText()+"."
						+serverPanel.getHostName3().getText()+"."
						+serverPanel.getHostName4().getText(), 
				Integer.valueOf(serverPanel.getPort().getText()), 
				serverPanel.getUserName().getText(), 
				new String(serverPanel.getPassword().getPassword()));
		//若连接成功
		if(success) {
			//替换服务器的文件
			success = ftpToServer.downLoad(msg, pathList);
			//断开连接
			ftpToServer.closeConnect(msg);
		}
		
		return success;
	}
	
	public static boolean upLoadFile(StringBuffer msg, FTPServerPanel serverPanel, List<PathPanel> pathList) {
		FTPToServer ftpToServer = new FTPToServer();
		boolean success = ftpToServer.connect(msg, 
				serverPanel.getHostName1().getText()+"."
						+serverPanel.getHostName2().getText()+"."
						+serverPanel.getHostName3().getText()+"."
						+serverPanel.getHostName4().getText(), 
				Integer.valueOf(serverPanel.getPort().getText()), 
				serverPanel.getUserName().getText(), 
				new String(serverPanel.getPassword().getPassword()));
		//若连接成功
		if(success) {
			//替换服务器的文件
			success = ftpToServer.upLoad(msg, pathList);
			//断开连接
			ftpToServer.closeConnect(msg);
		}
		
		return success;
	}
	
	public static StringBuffer savePathInfo(List<PathPanel> pathList) {
		StringBuffer msg = new StringBuffer();
		Properties props = new Properties();
		FileInputStream fin = null;
		FileOutputStream out = null;
		try {
			String path = getRootPath(CommonUtil.class, "CommonUtil.class");
			path += "cache/path";
			File fileDir = new File(path);
			if(!fileDir.exists()) {
				fileDir.mkdirs();
			}
			
			File[] files = fileDir.listFiles();
			if(files != null && files.length > 0) {
				for(File file : files) {
					if(file.isFile()) {
						file.delete();
					}
				}
			}
				
			File file = null;
			for(PathPanel pathPanel : pathList) {
				if(!"".equals(pathPanel.getHostPath().getText().trim()) && !"".equals(pathPanel.getLocalPath().getText().trim())) {
					file = new File(path+File.separatorChar+pathPanel.getIndex()+".properties");
					if(!file.exists()) {
						file.createNewFile();
					}
					fin = new FileInputStream(file);
					out = new FileOutputStream(file);
					props.load(fin);
					
					props.setProperty("path.index", pathPanel.getIndex());
					props.setProperty("path.type", pathPanel.getPathBox().getText());
					props.setProperty("path.hostPath", pathPanel.getHostPath().getText());
					props.setProperty("path.localPath", pathPanel.getLocalPath().getText());
					
					props.store(out, pathPanel.getIndex()+".properties");
					
					fin.close();
					out.close();
					
					props.clear();
				}
			}
		} catch (Exception e) {
			msg.append(CommonUtil.log("ERROR", "写入路径映射信息时出现异常:"+e.toString()));
		} finally {
			try {
				if(fin != null) {
					fin.close();
				}
				if(out != null) {
					out.close();
				}
				props.clear();
			} catch (IOException e) {
				msg.append(CommonUtil.log("ERROR", "关闭文件输入流时出现异常:"+e.toString()));
			}
		}
		
		return msg;
		
	}
	
	public static StringBuffer saveServerInfo(FTPServerPanel serverPanel) {
		StringBuffer msg = new StringBuffer();
		Properties props = new Properties();
		FileInputStream fin = null;
		FileOutputStream out = null;
		try {
			String path = getRootPath(CommonUtil.class, "CommonUtil.class");
			path += "cache/server";
			File fileDir = new File(path);
			if(!fileDir.exists()) {
				fileDir.mkdirs();
			}
			
			path += File.separatorChar + "server.properties";
			//创建文件
			File file = new File(path);
			if(!file.exists()) {
				file.createNewFile();
			}
			
			fin = new FileInputStream(path);
			out = new FileOutputStream(path);
			props.load(fin);
			
			props.setProperty("server.hostName", serverPanel.getHostName1().getText()+"."
					+serverPanel.getHostName2().getText()+"."
					+serverPanel.getHostName3().getText()+"."
					+serverPanel.getHostName4().getText());
			props.setProperty("server.port", serverPanel.getPort().getText());
			props.setProperty("server.userName", serverPanel.getUserName().getText());
			props.setProperty("server.password", new String(serverPanel.getPassword().getPassword()));
			
			props.store(out, "server.properties");
			
			fin.close();
			out.close();
			
			props.clear();
		} catch (Exception e) {
			msg.append(CommonUtil.log("ERROR", "写入服务器信息时出现异常:"+e.toString()));
		} finally {
			try {
				if(fin != null) {
					fin.close();
				}
				if(out != null) {
					out.close();
				}
				props.clear();
			} catch (IOException e) {
				msg.append(CommonUtil.log("ERROR", "关闭文件输入流时出现异常:"+e.toString()));
			}
		}
		
		return msg;
	}
	
	public static StringBuffer validateInfo(FTPServerPanel serverPanel, FilePathPanel filePathPanel) {
		StringBuffer msg = new StringBuffer();
		if("".equals(serverPanel.getHostName1().getText().trim()) 
				|| "".equals(serverPanel.getHostName2().getText().trim()) 
				|| "".equals(serverPanel.getHostName3().getText().trim()) 
				|| "".equals(serverPanel.getHostName4().getText().trim())) {
			msg.append("主机地址未设置完整!\n");
		}
		if("".equals(serverPanel.getPort().getText().trim())) {
			msg.append("端口未设置!\n");
		}
		if("".equals(serverPanel.getUserName().getText().trim())) {
			msg.append("用户名未设置!\n");
		}
		if(filePathPanel.getPathList() != null && filePathPanel.getPathList().size() > 0) {
			String hostPath = null;
			String localPath = null;
			boolean setFlag = false;
			for(PathPanel pathPanel : filePathPanel.getPathList()) {
				hostPath = pathPanel.getHostPath().getText().trim();
				localPath = pathPanel.getLocalPath().getText().trim();
				
				if("".equals(hostPath) && !"".equals(localPath)) {
					msg.append(pathPanel.getPathBox().getText()+"的服务器路径未指定!\n");
					setFlag = true;
				}
				if(!"".equals(hostPath) && "".equals(localPath)) {
					msg.append(pathPanel.getPathBox().getText()+"的本地路径未指定!\n");
					setFlag = true;
				}
				if(!"".equals(hostPath) && !"".equals(localPath)) {
					setFlag = true;
				}
			}
			if(!setFlag) {
				msg.append("服务器与本地路径未指定!\n");
			}
		} else {
			msg.append("服务器与本地路径未指定!\n");
		}
		
		return msg;
	}
	
	public static CommonBean getPathInfo() {
		CommonBean commonBean = new CommonBean();
		Properties props = new Properties();
		FileInputStream fin = null;
		try {
			commonBean.getMsgBuff().append(CommonUtil.log("INFO", "从缓存文件中读取路径的配置信息..."));
			String path = getRootPath(CommonUtil.class, "CommonUtil.class");
			path += "cache/path";
			File fileDir = new File(path);
			if(!fileDir.exists()) {
				fileDir.mkdirs();
				commonBean.getMsgBuff().append(CommonUtil.log("WARN", "暂无路径映射的缓存信息!"));
			} else {
				File[] files = fileDir.listFiles();
				if(files != null && files.length > 0) {
					String value = null;
					PathBean pathBean = null;
					for(File file : files) {
						fin = new FileInputStream(path + File.separatorChar + file.getName());
						props.load(fin);
						
						pathBean = new PathBean();
						value = props.getProperty("path.index");
						if(value != null && !"".equals(value.trim())) {
							pathBean.setIndex(value.trim());
						}
						value = props.getProperty("path.type");
						if(value != null && !"".equals(value.trim())) {
							pathBean.setType(value.trim());
						}
						value = props.getProperty("path.hostPath");
						if(value != null && !"".equals(value.trim())) {
							pathBean.setHostPath(value.trim());
						}
						value = props.getProperty("path.localPath");
						if(value != null && !"".equals(value.trim())) {
							pathBean.setLocalPath(value.trim());
						}
						
						commonBean.getPathList().add(pathBean);
						
						fin.close();
						props.clear();
					}
					commonBean.getMsgBuff().append(CommonUtil.log("SUCCESS", "读取完成!"));
				} else {
					commonBean.getMsgBuff().append(CommonUtil.log("WARN", "暂无路径映射的缓存信息!"));
				}
			}
		} catch (Exception e) {
			commonBean.getMsgBuff().append(CommonUtil.log("ERROR", "读取路径映射信息时出现异常:"+e.toString()));
		} finally {
			try {
				if(fin != null) {
					fin.close();
				}
				props.clear();
			} catch (IOException e) {
				commonBean.getMsgBuff().append(CommonUtil.log("ERROR", "关闭文件输入流时出现异常:"+e.toString()));
			}
		}
		
		return commonBean;
	}
	
	public static CommonBean getServerInfo() {
		CommonBean commonBean = new CommonBean();
		Properties props = new Properties();
		FileInputStream fin = null;
		try {
			commonBean.getMsgBuff().append(CommonUtil.log("INFO", "从缓存文件中读取服务器的配置信息..."));
			String path = getRootPath(CommonUtil.class, "CommonUtil.class");
			path += "cache/server";
			File fileDir = new File(path);
			if(!fileDir.exists()) {
				fileDir.mkdirs();
				commonBean.getMsgBuff().append(CommonUtil.log("WARN", "暂无服务器的配置缓存信息!"));
			} else {
				path += File.separatorChar + "server.properties";
				//创建文件
				File file = new File(path);
				if(!file.exists()) {
					file.createNewFile();
					commonBean.getMsgBuff().append(CommonUtil.log("WARN", "暂无服务器的配置缓存信息!"));
				} else {
					fin = new FileInputStream(path);
					props.load(fin);
					
					String value = props.getProperty("server.hostName");
					if(value != null && !"".equals(value.trim())) {
						commonBean.setHostName(value.trim());
					}
					value = props.getProperty("server.port");
					if(value != null && !"".equals(value.trim())) {
						commonBean.setPort(value.trim());
					}
					value = props.getProperty("server.userName");
					if(value != null && !"".equals(value.trim())) {
						commonBean.setUserName(value.trim());
					}
					value = props.getProperty("server.password");
					if(value != null && !"".equals(value.trim())) {
						commonBean.setPassword(value.trim());
					}
					
					fin.close();
					props.clear();
					commonBean.getMsgBuff().append(CommonUtil.log("SUCCESS", "读取完成!"));
				}
			}
		} catch (Exception e) {
			commonBean.getMsgBuff().append(CommonUtil.log("ERROR", "读取服务器信息时出现异常:"+e.toString()));
		} finally {
			try {
				if(fin != null) {
					fin.close();
				}
				props.clear();
			} catch (IOException e) {
				commonBean.getMsgBuff().append(CommonUtil.log("ERROR", "关闭文件输入流时出现异常:"+e.toString()));
			}
		}
		
		return commonBean;
	}
	
	private static String getRootPath(Class<?> cls, String clsStr) {
		String result = cls.getResource(clsStr).toString();
		
		int index = result.indexOf("WEB-INF");
		if (index == -1) {
			index = result.indexOf("bin");
		}
		if (index == -1) {
			index = result.indexOf("lib");
		}
		if (index == -1) {
			index = result.indexOf(".jar!");
		}
		
		if(index > 0) {
			result = result.substring(0, index);
		}
		
		if(isWindows()) {
			index = result.lastIndexOf("/");
			if(index == -1) {
				index = result.lastIndexOf("\\");
			}
			if(index > 0) {
				result = result.substring(0, index);
			}
		} else {
			index = result.lastIndexOf("/");
			if(index > 0) {
				result = result.substring(0, index);
			}
		}
		
		if (result.startsWith("ws")) {
			result = result.substring(2);
		}
		
		if (result.startsWith("jar:file:")) {
			if(isWindows()){
				result = result.substring(10);
			}else{
				result = result.substring(9);
			}
		}
		if (result.startsWith("zip:")) {
			result = result.substring(4);
		}
		
		if(result.startsWith("file:")){
			result = result.substring(6);
		}

		return result + File.separatorChar;
	}
	
	/**
	 * 判断当前操作系统是不是window
	 * 
	 * @return boolean
	 */
	private static boolean isWindows() {
		boolean flag = false;
		if (System.getProperties().getProperty("os.name").toUpperCase()
				.indexOf("WINDOWS") != -1) {
			flag = true;
		}
		return flag;
	}
}


 

package util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import panel.PathPanel;

public class FTPToServer {
	private FTPClient ftpClient = null;
	//上传文件
	private BufferedInputStream buffIn = null;
	//下载文件
	private BufferedOutputStream buffOut = null;
	
	public FTPToServer() {
		ftpClient = new FTPClient();
		
		ftpClient.setConnectTimeout(60000);
	}
	
	public boolean connect(StringBuffer msg, String hostname, int port, String userName, String password) {
		boolean success = true;
		try {
			msg.append(CommonUtil.log("INFO", "正在尝试连接服务器..."));
			ftpClient.connect(hostname, port);
			int reply = ftpClient.getReplyCode();
			msg.append(CommonUtil.log("INFO", "返回码:【"+reply+"】"));
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftpClient.disconnect();
				msg.append(CommonUtil.log("ERROR", "服务器拒绝连接!"));
				success = false;
			} else {
				msg.append(CommonUtil.log("INFO", "正在尝试登录服务器..."));
				success = ftpClient.login(userName, password);
				if(success) {
					msg.append(CommonUtil.log("SUCCESS", "登录服务器成功!"));
					ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
				} else {
					msg.append(CommonUtil.log("ERROR", "登录的用户名或者密码不正确!"));
				}
			}
		} catch (Exception e) {
			success = false;
			msg.append(CommonUtil.log("ERROR", "连接服务器时出现异常:"+e.toString()));
		}
		
		return success;
	}
	
	public boolean upLoad(StringBuffer msg, List<PathPanel> pathList) {
		boolean success = true;
		try {
			File localDir = null;
			for(PathPanel pPanel : pathList) {
				localDir = new File(pPanel.getLocalPath().getText());
				
				ftpClient.changeWorkingDirectory(pPanel.getHostPath().getText());
				
				if(localDir != null && localDir.exists() && localDir.isDirectory()) {
					upLoadFolder(localDir);
					msg.append(CommonUtil.log("SUCCESS", "路径:"+pPanel.getLocalPath().getText()+",替换本地文件至服务器成功!"));
				} else {
					success = false;
					msg.append(CommonUtil.log("WARN", "路径:"+pPanel.getLocalPath().getText()+",无效!"));
				}
			}
		} catch (Exception e) {
			success = false;
			msg.append(CommonUtil.log("ERROR", "替换本地文件至服务器时出现异常:"+e.toString()));
		} finally {
			try{
				if(buffIn != null) {
					buffIn.close();
				}
			} catch (Exception e){
				success = false;
				msg.append(CommonUtil.log("ERROR", "关闭文件输入流时出现异常:"+e.toString()));
			}
		}
		return success;
	}
	
	public boolean downLoad(StringBuffer msg, List<PathPanel> pathList) {
		boolean success = true;
		try {
			File file = null;
			for(PathPanel pPanel : pathList) {
				ftpClient.changeWorkingDirectory(pPanel.getHostPath().getText());
				
				file = new File(pPanel.getLocalPath().getText());
				if(file != null && file.exists() && file.isDirectory()) {
					//备份一份
					downLoadFolder(pPanel.getLocalPath().getText()+File.separatorChar+"bak");
					//下载一份用于修改
					downLoadFolder(pPanel.getLocalPath().getText());
					
					msg.append(CommonUtil.log("SUCCESS", "路径:"+pPanel.getHostPath().getText()+",已下载至本地!"));
					
				} else {
					success = false;
					msg.append(CommonUtil.log("WARN", "路径:"+pPanel.getHostPath().getText()+",无效!"));
				}
			}
		} catch (Exception e) {
			success = false;
			msg.append(CommonUtil.log("ERROR", "下载服务器文件至本地时出现异常:"+e.toString()));
		} finally {
			try{
				if(buffOut != null) {
					buffOut.close();
				}
			} catch (Exception e){
				success = false;
				msg.append(CommonUtil.log("ERROR", "关闭文件输入流时出现异常:"+e.toString()));
			}
		}
		return success;
	}

	
	public void closeConnect(StringBuffer msg){
		try{
			if(ftpClient!=null){
				ftpClient.logout();
				msg.append(CommonUtil.log("SUCCESS", "登出服务器成功!"));
				ftpClient.disconnect();
				msg.append(CommonUtil.log("SUCCESS", "断开服务器连接成功!"));
			}
		}catch(Exception e){
			msg.append(CommonUtil.log("ERROR", "断开连接服务器时出现异常:"+e.toString()));
		}
	}
	
	private void upLoadFolder(File folder) throws Exception {
		File[] files = folder.listFiles();
		if(files != null && files.length > 0) {
			
			for(File file : files) {
				if(file.exists()) {
					if(file.isDirectory() && !"bak".equalsIgnoreCase(file.getName())) {
						ftpClient.makeDirectory(file.getName());
						ftpClient.changeWorkingDirectory(file.getName());
						
						upLoadFolder(file);
						
						ftpClient.changeToParentDirectory();
					} else {
						buffIn = new BufferedInputStream(new FileInputStream(file));
						ftpClient.storeFile(new String(file.getName().getBytes("GBK"),"iso-8859-1"), buffIn);
						
						buffIn.close();
					}

				}
			}
		}
	}
	
	private void downLoadFolder(String localDir) throws Exception {
		File tempFile = new File(localDir);
		if(!tempFile.exists()) {
			tempFile.mkdir();
		}
		
		FTPFile[] hostFiles = ftpClient.listFiles();
		
		if(hostFiles != null && hostFiles.length > 0) {
			
			File localFile = null;
			String localDirTemp = null;
			
			for(FTPFile file : hostFiles) {
				localDirTemp = localDir+File.separatorChar+file.getName();
				
				if(file.isDirectory()) {
					localFile = new File(localDirTemp);
					if(!(localFile != null && localFile.exists())) {
						localFile.mkdir();
					}
					ftpClient.changeWorkingDirectory(file.getName());
					
					downLoadFolder(localDirTemp);
					
					ftpClient.changeToParentDirectory();
				} else {
					buffOut = new BufferedOutputStream(new FileOutputStream(localDirTemp));
					ftpClient.retrieveFile(file.getName(), buffOut);
				
					buffOut.close();
				}
			}
		}
	}
}


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值