Client
/** * File Upload client * * * @author Chen.lin * */public class Uploadclient extends JFrame {/** * * */PRI
Vate static final Long serialversionuid = -8243692833693773812l;
Private String ip;//server IP private int port;//port private Properties prop; Private list<filebean> Filebeans = new arraylist<filebean> ();//The collection of files read from file.xml private socket socket;
Client socket private Bytearrayinputstream Bais;
Private Sequenceinputstream sis;
Private Bufferedoutputstream Bos;
Private InputStream FS;
Public uploadclient () {//Initialization data initdatas ();
Start uploading Files startuploadfile ();
Set window Properties Initviews ();
private void Initviews () {settitle ("Upload client");
Getcontentpane (). setlayout (NULL);
SetBounds (160, 200, 440, 300);
Setdefaultcloseoperation (Dispose_on_close);
SetVisible (TRUE); /** * Start uploading files .... */public void STARTUPLOADFIle () {try {socket = new socket (IP, port);
if (!socket.isclosed () && socket.isconnected ()) {Logger.log ("Client connection succeeded ...");
SYSTEM.OUT.PRINTLN ("Client connection succeeded ...");
else {Logger.log ("Connection failed, please contact the developer ...");
Joptionpane.showmessagedialog (NULL, "Connection failed, please contact developer");
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 () = =-fs = Conn.getinputstream ();
}else {Logger.log (Error message: File network path error: + 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 >) {Logger.log ("file exceeds 70M, cannot upload");
Return }//define a 256-byteArea to save file information.
Byte[] B = filename.getbytes ();
Byte[] info = arrays.copyof (b, 256);
Bais = new Bytearrayinputstream (info);
SIS = new Sequenceinputstream (Bais, FS);
if (socket.isclosed ()) {Logger.log ("Reconnect successful!");
System.out.println ("Reconnect successful!");
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 ();
}//Close Socket.shutdownoutput (); String RESult = Br.readline ();
Logger.log (Filebean.getname () + "upload:" + result);
if ("Success". Equals (Result.trim ())) {filebean.setstate (1);
Xmlutil.changefilestate (Prop.getproperty ("Xmlpath"), Filebean);
} br.close ();
A 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 ();
} }/** * Initialization data * * @throws unknownhostexception * @throws Exception/pri
vate 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);
Because read the remote XML, more time-consuming, so put the thread running 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 V
OID run () {try {new uploadclient ();
System.exit (0);
catch (Exception e) {e.printstacktrace ();
}
}
}); }
}
Server-side code
/** * File Upload server * * @author chen.lin * * */public class Uploadserver extends JFrame {/** * * */PRI
Vate 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 ("Upload Server");
Getcontentpane (). setlayout (NULL);
JLabel label = new JLabel ("Listening window:");
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);
/** * Start service/FINAL JButton btnstart = new JButton ("Boot server");
Btnstart.addactionlistener (new ActionListener () {public void actionperformed (ActionEvent e) { Port.setenabled (FALSE);
Control is not variable in black and white Btnstart.setenabled (FALSE);
Isrun = true;
New Thread (New Runnable () {@Override public void run () {
try {server = new ServerSocket (Integer.parseint (Port.gettext ()));
SYSTEM.OUT.PRINTLN ("The server started ...");
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 ("Stop Server");
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 Ru
N () {try {new uploadserver ();
catch (Exception e) {e.printstacktrace ();
}
}
}); /** * File transfer memory consumption, so must be placed in a thread run/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.ge
Tinputstream ());
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 + "/" + fi Lename));
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 + "file transfer succeeded");
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 ();
} }
}
}
}
Related tool Classes
/**
* Record log information
* @author chen.lin
*
*
/public class Logger {public
static void log (String name) { c7/>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 (); c23/>}}}
/** * Read Profile tool * @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 ();
The public static Properties Getprop () {return prop;
public static void Main (string[] args) {String Xmlpath = (String) proputil.getprop (). Get ("FilePath");
System.out.println (Xmlpath); }
}
/** * Text Tool * @author Chen.lin * */public class Textutil {public static Boolean IsEmpty (String text) {if (text = = NULL | |
'. Equals (Text.trim ()) {return true;
return false; }
}
/** * XML file parsing and generating * * @author Chen.lin */public class Xmlutil {/** * Get file information from XML file * * @par AM Xmlpath * @return * @throws Exception/public static list<filebean> Getfilebeanfromxml (Strin
G 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 Filebe
An ();
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://Add object to list if ("File". Equals (Parser.getname ()) && b
EAN!= null && bean.getstate () = = 0) {list.add (bean); Bean = null;
} break;
//The current resolution position ends, pointing to the next location EventType = Parser.next ();
} return list; /** * Modify XML content * * @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 (