【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+"
"; } 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(" !
"); } if("".equals(serverPanel.getPort().getText().trim())) { msg.append(" !
"); } if("".equals(serverPanel.getUserName().getText().trim())) { msg.append(" !
"); } 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()+" !
"); setFlag = true; } if(!"".equals(hostPath) && "".equals(localPath)) { msg.append(pathPanel.getPathBox().getText()+" !
"); setFlag = true; } if(!"".equals(hostPath) && !"".equals(localPath)) { setFlag = true; } } if(!setFlag) { msg.append(" !
"); } } else { msg.append(" !
"); } 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();
				}
			}
		}
	}
}