檔案上傳案例及多執行緒版本
阿新 • • 發佈:2019-01-05
檔案上傳案例
程式碼演示:
1 public class TCPServer { 2 public static void main(String[] args) throws IOException { 3 ServerSocket server=new ServerSocket(5555); 4 Socket socket=server.accept(); 5 //明確資料來源 6 InputStream in=socket.getInputStream(); 7 //明確目的地 8 File file=new File("x:\\upload"); 9 if(!file.exists()){ 10 file.mkdirs(); 11 } 12 //域名+毫秒值 13 String filename="oracle"+System.currentTimeMillis()+".jpg"; 14 FileOutputStream fos=new FileOutputStream(file+File.separator+filename); 15 //複製 16 int len=0; 17 byte[] bytes=new byte[1024]; 18 while((len=in.read(bytes))!=-1){ 19 fos.write(bytes,0,len); 20 } 21 22 //回覆客戶端 23 OutputStream out=socket.getOutputStream(); 24 out.write("上傳成功!".getBytes()); 25 //釋放資源 26 server.close(); 27 fos.close(); 28 } 29 }
1 public class TCPClinet { 2 public static void main(String[] args) throws IOException { 3 Socket socket=new Socket("192.168.1.171",7000); 4 OutputStream out=socket.getOutputStream(); 5 //明確資料來源 6 FileInputStream fis=new FileInputStream("x:\\test\\img1.jpg"); 7 int len=0; 8 byte[] bytes=new byte[1024]; 9 //檔案複製 10 while((len=fis.read(bytes))!=-1){ 11 out.write(bytes,0,len); 12 } 13 //告訴伺服器端不要在讀了到末尾了 14 socket.shutdownOutput(); 15 //伺服器端回覆 16 InputStream in=socket.getInputStream(); 17 len=in.read(bytes); 18 System.out.println(new String(bytes, 0, len)); 19 //釋放資源 20 fis.close(); 21 socket.close(); 22 } 23 24 }
檔案上傳案例多執行緒版本
程式碼演示:
1 public class Demo { 2 public static void main(String[] args) throws IOException { 3 ServerSocket server=new ServerSocket(6000); 4 while(true){ 5 Socket socket=server.accept(); 6 new Thread(new Upload(socket)).start(); 7 } 8 } 9 }
1 public class Upload implements Runnable{ 2 private Socket socket; 3 public Upload(Socket socket){ 4 this.socket=socket; 5 } 6 public void run() { 7 //明確資料來源 8 FileOutputStream fos=null; 9 try { 10 InputStream in= socket.getInputStream(); 11 //明確目的地 12 File file=new File("x:\\upload"); 13 if(!file.exists()){ 14 file.mkdirs(); 15 } 16 //域名+毫秒值 17 String filename="oracle"+System.currentTimeMillis()+".jpg"; 18 fos=new FileOutputStream(file+File.separator+filename); 19 //複製 20 int len=0; 21 byte[] bytes=new byte[1024]; 22 while((len=in.read(bytes))!=-1){ 23 fos.write(bytes,0,len); 24 } 25 //回覆客戶端 26 OutputStream out=socket.getOutputStream(); 27 out.write("上傳成功!".getBytes()); 28 } catch (IOException e) { 29 e.printStackTrace(); 30 }finally{ 31 //釋放資源 32 try { 33 fos.close(); 34 } catch (IOException e) { 35 e.printStackTrace(); 36 } 37 } 38 } 39 }