Java implements file upload on the server and client, and java implements File Upload

Source: Internet
Author: User

Java implements file upload on the server and client, and java implements File Upload

The examples in this article share the specific code of the Java File Upload server and client for your reference. The specific content is as follows:

File Upload Server:

/*** Use the TCP protocol to implement the upload function on the server side * idea: * Create a ServerSocket * Wait for the client to connect * And then enable the sub-thread, pass the Socket obtained by the connection to the sub-thread * For Loop * @ author yajun **/public class UploadServer {public static void main (String [] args) {UploadServer server = new UploadServer (); UploadThread command = new UploadThread (); server. start (command);}/*** function: receives connections, starts sub-threads, and loops * @ param command to download sub-thread objects, this object implements the Runnable interface */private void start (UploadThread command) {// Local variable ServerSocket serverSocket = null; Socket transSocket; // business logic try {serverSocket = new ServerSocket (55555); while (true) {System. out. println ("waiting for connection ...... "); TransSocket = serverSocket. accept (); int I = 0; I ++; System. out. println ("+" + I + ""); // do not close the thread after downloading ??? Command. setSocket (transSocket); executors.newfixedthreadpool(52.16.exe cute (command);} // exception capture} catch (IOException e) {e. printStackTrace (); // close the resource} finally {try {serverSocket. close ();} catch (IOException e) {e. printStackTrace () ;}// End of try} // End of connect @ Test public void testConnect () {// Test task: run the server first, then run the Client Multiple times. If the server segment can continuously create sub-threads, the test is successful // test preparation: constructs a thread to simulate the download thread UploadThread command = new UploadTh Read (); start (command) ;}@ Test public void testDown () throws IOException {byte [] buf; ByteArrayInputStream bis; String str = "canglaoshi. avi \ ncontent, content, content "; buf = str. getBytes (); bis = new ByteArrayInputStream (buf); UploadThread ut = new UploadThread (); ut. down (bis) ;}// subthread class UploadThread implements Runnable {Socket socket; public UploadThread () {} public UploadThread (Socket so Cket) {this. socket = socket ;}@ Override public void run () {InputStream in; try {in = socket. getInputStream (); down (in); // Exception Handling} catch (IOException e) {e. printStackTrace ();} finally {try {socket. close ();} catch (IOException e) {e. printStackTrace () ;}/// test code/* try {Thread. sleep (1, 5000); System. out. println (Thread. currentThread (). getName () + ", copied");} catch (InterruptedException e) {e. printSt AckTrace ();} */} // End of run public void setSocket (Socket socket) {this. socket = socket;} // download method/*** objective: to write data in InputStream to a local device * idea: * 1. it is best to pass in the input stream instead of directly obtaining the input stream from the Socket. The input has a unit test * 2. read the file name from the input stream * 3. create a file and file output stream * 4. read the file content from the input stream to the file output stream * 5. * @ throws IOException */public void down (InputStream in) throws IOException {// local variable char ch; char [] nameArr = new char [256]; byte [] buf = new byte [1024]; String name = ""; OutputStream out = null; // business logic try {// Step 1: Get the file name and construct the output stream int I = 0; while (ch = (char) in. read ())! = '\ N') {nameArr [I ++] = ch;} // name = nameArr. toString (); // The character array cannot be converted to a String. Use the following statement name = new String (nameArr); System. out. println ("the file to be downloaded is:" + name); out = new FileOutputStream ("src \ down \" + name); // Step 2: write Other content in the input stream to the file int len; while (len = in. read (buf ))! =-1) {out. write (buf, 0, len);} out. flush (); // exception capture} catch (IOException e) {e. printStackTrace (); // close the resource} finally {// question: Can I put two captures together? How can I handle exceptions when closing the stream? In. close (); out. close () ;}// debug System. out. println (name) ;}// End of UploadThread

File Upload client:

/*** Client that implements the upload function using the TCP protocol * @ author yajun */public class UploadClient {public static void main (String [] args) {UploadClient client = new UploadClient (); client. upload ("src \ Thursday \ AsListTest. java ");}/*** function: upload a file to the server * 1. establish a connection to the server * 2. get output stream * 3. write the file content to the output stream * 4. get server response */private void upload (String name) {Socket socket = null; OutputStream out; try {socket = new Socket ("127.0.0.1", 55555); out = soc Ket. getOutputStream (); write2OutputStream (name, out); // exception capture} catch (UnknownHostException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace () ;}@ Test public void testUpload () {upload ("src \ status. xml ");}/*** function: imports the file name and output stream, writes the file to the output stream * @ param path * @ throws IOException */private void write2OutputStream (String path, outputStream out) throws IOException {FileInputStream FCM = Null; byte [] buf = new byte [1024]; String fileName = ""; // business logic try {// 1. write File Name fileName = path. substring (path. lastIndexOf ('\') + 1); System. out. println ("the file name you want to upload is:" + fileName); out. write (fileName. getBytes (); out. write ('\ n'); // 2. write File Content. read (buf ))! =-1) {out. write (buf, 0, len);} out. flush (); // Exception Handling} catch (IOException e) {e. printStackTrace (); // closes the resource} finally {FCM. close (); out. close () ;}// End of upload @ Test public void testWrite2OutputStream () throws IOException {ByteArrayOutputStream out = null; try {out = new ByteArrayOutputStream (); write2OutputStream ("src \ status. xml ", out); System. out. println (out. toString ("UTF-8");} catch (IOException e) {e. printStackTrace ();} finally {out. close ();}}}

This article has been compiled into Java upload operation tips summary. You are welcome to learn and read this article.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.