用戶端
/** * 檔案上傳用戶端 * * @author chen.lin * */public class UploadClient extends JFrame { /** * */ private static final long serialVersionUID = -8243692833693773812L; private String ip;// 伺服器ip private int port;// 連接埠 private Properties prop; private List<FileBean> fileBeans = new ArrayList<FileBean>();// 從file.xml讀到的檔案集合 private Socket socket; // 用戶端socket private ByteArrayInputStream bais; private SequenceInputStream sis; private BufferedOutputStream bos; private InputStream fs; public UploadClient() { // 初始化資料 initDatas(); // 開始上傳檔案 startUploadFile(); // 設定視窗屬性 initViews(); } private void initViews() { setTitle("上傳用戶端"); getContentPane().setLayout(null); setBounds(160, 200, 440, 300); setDefaultCloseOperation(DISPOSE_ON_CLOSE); setVisible(true); } /** * 開始上傳檔案.... */ public void startUploadFile() { try { socket = new Socket(ip, port); if (!socket.isClosed() && socket.isConnected()) { Logger.log("用戶端串連成功...."); System.out.println("用戶端串連成功...."); } else { Logger.log("串連失敗, 請與開發人員聯絡...."); JOptionPane.showMessageDialog(null, "串連失敗, 請與開發人員聯絡"); return; } for (FileBean fileBean : fileBeans) { String filePath = fileBean.getPath(); Logger.log("filepath===" + filePath); File file = null; if (filePath != null && !"".equals(filePath.trim())) { int indexOf = filePath.lastIndexOf("/"); String fileName = filePath.substring(indexOf + 1); if (filePath.startsWith("http://")) { URL url = new URL(filePath); file = new File(filePath); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(5000); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); if (conn.getResponseCode() == 200) { fs = conn.getInputStream(); }else { Logger.log("錯誤資訊:檔案網路路徑錯誤:" + filePath); } }else { file = new File(fileBean.getPath()); fs = new FileInputStream(file); } Logger.log("filename=" + fileName); long fileSize = file.length(); Logger.log("filesize===" + fileSize); if (fileSize / 1024 / 1024 > 70) { Logger.log("檔案超過了70M,不能上傳"); return; } //定義一個256位元組的地區來儲存檔案資訊。 byte[] b = fileName.getBytes(); byte[] info = Arrays.copyOf(b, 256); bais = new ByteArrayInputStream(info); sis = new SequenceInputStream(bais, fs); if (socket.isClosed()) { Logger.log("重新串連成功!"); System.out.println("重新串連成功!"); socket = new Socket(ip, port); } bos = new BufferedOutputStream(socket.getOutputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); byte[] buf = new byte[1024]; int len = 0; while ((len = sis.read(buf)) != -1) { bos.write(buf, 0, len); bos.flush(); } //關閉 socket.shutdownOutput(); String result = br.readLine(); Logger.log(fileBean.getName() + "上傳:" + result); if ("success".equals(result.trim())) { fileBean.setState(1); XmlUtil.changeFileState(prop.getProperty("xmlPath"), fileBean); } br.close(); } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (bos != null) { bos.close(); } if (sis != null) { sis.close(); } if (fs != null) { fs.close(); } if (bais != null) { bais.close(); } if (socket != null) { socket.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * 初始化資料 * * @throws UnknownHostException * @throws Exception */ private void initDatas() { try { prop = PropUtil.getProp(); ip = prop.getProperty("ip"); if (ip.startsWith("http://")) { ip = InetAddress.getByName(ip).getHostAddress(); } port = Integer.parseInt(prop.getProperty("port")); final String xmlPath = prop.getProperty("xmlPath"); Logger.log("xmlPath===" + xmlPath); System.out.println("xmlPath===" + xmlPath); // 因為讀的是遠程xml,比較耗時,所以放線上程裡運行 ExecutorService executorService = Executors.newCachedThreadPool(); ArrayList<Future<List<FileBean>>> list = new ArrayList<Future<List<FileBean>>>(); list.add(executorService.submit(new CallThread(xmlPath))); for (Future<List<FileBean>> fs : list) { List<FileBean> fileBean = fs.get(); fileBeans.addAll(fileBean); } } catch (Exception e) { e.printStackTrace(); Logger.log("error:" + e.getMessage()); //JOptionPane.showMessageDialog(null, "error:" + e.getMessage()); } } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { new UploadClient(); System.exit(0); } catch (Exception e) { e.printStackTrace(); } } }); }}
伺服器端代碼
/** * 檔案上傳伺服器端 * * @author chen.lin * */public class UploadServer extends JFrame { /** * */ private static final long serialVersionUID = -5622620756755192667L; private JTextField port; private ServerSocket server; private volatile boolean isRun = false; private ExecutorService pool = Executors.newFixedThreadPool(10); public UploadServer() { setTitle("上傳伺服器"); getContentPane().setLayout(null); JLabel label = new JLabel("監聽視窗:"); label.setBounds(86, 80, 74, 15); getContentPane().add(label); port = new JTextField("9000"); port.setBounds(178, 77, 112, 21); getContentPane().add(port); port.setColumns(10); /** * 啟動服務 */ final JButton btnStart = new JButton("啟動伺服器"); btnStart.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { port.setEnabled(false); // 控制項黑白不可變 btnStart.setEnabled(false); isRun = true; new Thread(new Runnable() { @Override public void run() { try { server = new ServerSocket(Integer.parseInt(port.getText())); System.out.println("伺服器開始啟動了........"); while (isRun) { pool.execute(new UploadThread(server.accept())); }; } catch (NumberFormatException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); pool.shutdown(); } } }).start(); } }); btnStart.setBounds(73, 145, 93, 23); getContentPane().add(btnStart); JButton btnStop = new JButton("停止伺服器"); btnStop.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { port.setEnabled(true); btnStart.setEnabled(true); isRun = false; server = null; } }); btnStop.setBounds(209, 145, 93, 23); getContentPane().add(btnStop); setBounds(600, 200, 380, 300); setDefaultCloseOperation(DISPOSE_ON_CLOSE); setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { new UploadServer(); } catch (Exception e) { e.printStackTrace(); } } }); } /** * 進行檔案傳輸耗記憶體,所以必須放線上程中運行 */ class UploadThread implements Runnable { private Socket socket; private SimpleDateFormat sdf; private BufferedInputStream bis; private BufferedOutputStream bos; UploadThread(Socket socket) { this.socket = socket; sdf = new SimpleDateFormat("yyyyMMddHH"); } @Override public void run() { try { bis = new BufferedInputStream(socket.getInputStream()); byte[] info = new byte[256]; bis.read(info); String fileName = new String(info).trim(); String filePath = PropUtil.getProp().getProperty("filePath"); String fullPath = filePath + "/" + sdf.format(new Date()); File dirs = new File(fullPath); if (!dirs.exists()) { dirs.mkdirs(); } PrintWriter pw = new PrintWriter(socket.getOutputStream(),true); if (!TextUtil.isEmpty(fileName)) { bos = new BufferedOutputStream(new FileOutputStream(fullPath + "/" + fileName)); byte[] buf = new byte[1024]; int len = 0; while ((len = bis.read(buf)) != -1) { bos.write(buf, 0, len); bos.flush(); } System.out.println(fileName + " 檔案傳輸成功"); pw.println("success"); }else { pw.println("failure"); } pw.close(); } catch (IOException e) { e.printStackTrace(); } finally{ try { if (bos != null) { bos.close(); } if (bis != null) { bis.close(); } if (socket != null) { socket.close(); } } catch (IOException e) { e.printStackTrace(); } } } }}
相關的工具類
/** * 記錄日誌資訊 * @author chen.lin * */public class Logger { public static void log(String name){ try { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH"); String path = "d:/upload_log/" + sdf.format(new Date()) ; File file = new File(path); if (!file.exists()) { file.mkdirs(); } FileOutputStream out = new FileOutputStream(new File(path + "/log.txt"), true); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out)); bw.write(name + "\r\n"); bw.flush(); bw.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}
/** * 讀取設定檔工具 * @author chen.lin * */public class PropUtil { private static Properties prop; static{ prop = new Properties(); //InputStream inStream = PropUtil.class.getClassLoader().getResourceAsStream("d:/files/config.properties"); try { InputStream inStream = new FileInputStream(new File("d:/files/config.properties")); prop.load(inStream); } catch (IOException e) { e.printStackTrace(); } } public static Properties getProp(){ return prop; } public static void main(String[] args) { String xmlPath = (String) PropUtil.getProp().get("filePath"); System.out.println(xmlPath); }}
/** * 文本工具 * @author chen.lin * */public class TextUtil { public static boolean isEmpty(String text){ if (text == null || "".equals(text.trim())) { return true; } return false; }}
/** * xml檔案解析與產生 * * @author chen.lin * */public class XmlUtil { /** * 從xml檔案中擷取檔案資訊 * * @param xmlPath * @return * @throws Exception */ public static List<FileBean> getFileBeanFromXml(String xmlPath) throws Exception { List<FileBean> list = null; if (TextUtil.isEmpty(xmlPath)) { return null; } XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser parser = factory.newPullParser(); InputStream inputStream = null; if (xmlPath.startsWith("http://")) { URL url = new URL(xmlPath); inputStream = url.openStream(); } else { inputStream = new FileInputStream(new File(xmlPath)); } parser.setInput(inputStream, "UTF-8"); int eventType = parser.getEventType(); FileBean bean = null; while (eventType != XmlPullParser.END_DOCUMENT) { switch (eventType) { case XmlPullParser.START_DOCUMENT: list = new ArrayList<FileBean>(); break; case XmlPullParser.START_TAG: if ("file".equals(parser.getName())) { bean = new FileBean(); bean.setId(parser.getAttributeValue(0)); } else if ("name".equals(parser.getName())) { bean.setName(parser.nextText()); } else if ("path".equals(parser.getName())) { bean.setPath(parser.nextText()); } else if ("state".equals(parser.getName())) { int state = Integer.parseInt(parser.nextText()); bean.setState(state); } break; case XmlPullParser.END_TAG: // 添加對象到list中 if ("file".equals(parser.getName()) && bean != null && bean.getState() == 0) { list.add(bean); bean = null; } break; } // 當前解析位置結束,指向下一個位置 eventType = parser.next(); } return list; } /** * 修改xml內容 * * @param xmlPath * @param bean */ public static void changeFileState(String xmlPath, FileBean bean) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = null; if (xmlPath.startsWith("http://")) { URL url = new URL(xmlPath); doc = db.parse(url.openStream()); } else { doc = db.parse(