java-Socket文件传输
生活随笔
收集整理的這篇文章主要介紹了
java-Socket文件传输
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Socket文件傳輸
//發送文件System.out.println("啟動服務器");//1.套接字準備連接主機,并向對應的端口發送數據Socket s = new Socket("localhost", 8888);//2.獲取輸出流,準備發送數據OutputStream os = s.getOutputStream();//3.字節緩沖流BufferedOutputStream bos = new BufferedOutputStream(os);//4.準備文件String str = "G:/douban.html";File file = new File(str);//5. 讀取到內存,使用字節緩沖流FileInputStream fis = new FileInputStream(file);BufferedInputStream bis = new BufferedInputStream(fis);/** 6.讀寫過程*/byte[] b = new byte[1024];int i = -1;while((i=bis.read(b)) != -1){bos.write(b, 0, i);}System.out.println("文件發送完畢!");//7.關流bis.close();fis.close();bos.close();os.close();注意:必須關閉流。發送文件,本質上是:從磁盤中寫入到內存中,再從內存中寫出到服務器。
//接收文件System.out.println("準備好接收了....");//1.服務端,監聽本機端口8888ServerSocket ss = new ServerSocket(8888);//2.套接字對象Socket accept = ss.accept();//3.接收數據InputStream is = accept.getInputStream();BufferedInputStream bis = new BufferedInputStream(is);//4.創建文件夾接收,使用字符輸出流File file = new File("G:/java/douban.html");FileOutputStream fos = new FileOutputStream(file);BufferedOutputStream bos = new BufferedOutputStream(fos);//5.讀寫過程byte[] b = new byte[1024];int len = -1;while((len=bis.read(b))!=-1){bos.write(b, 0, len);}System.out.println("文件接收完畢!");//6.關流bos.close();fos.close();bis.close();is.close();注意:必須關流。接收文件,本質上是:從服務器寫入到內存中,再從內存中寫出到磁盤。
總結
以上是生活随笔為你收集整理的java-Socket文件传输的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: OPCUA标准java实现 Milo库
- 下一篇: 永远的超级玛丽