JavaIO流实现文件传输
生活随笔
收集整理的這篇文章主要介紹了
JavaIO流实现文件传输
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
線程類
服務器端要用到線程,每次有文件上傳都要用到這個類,所以最好將這個類抽離出來專門處理文件上傳業務的線程類。
相關代碼如下:
//處理文件上傳業務的線程類 public class ServerThread implements Runnable{private Socket socket;public ServerThread(Socket socket) {this.socket = socket;}//負責獲取客戶端傳遞文件的數據,同時將數據寫入到本地的某個文件中@Overridepublic void run() {//獲取客戶端對應的ip地址String ip=socket.getInetAddress().getHostAddress();//創建一個用于計數文件上傳次數的變量int count=1;try {//獲取輸入流對象InputStream in=socket.getInputStream();//文件對象File parentFile=new File("E:/upload/");//如果文件夾目錄不存在自動創建此文件夾if(!parentFile.exists()){parentFile.mkdir();//創建此文件夾}//創建一個具體的File對象,將來存儲客戶端傳遞的數據,寫入到此File中//在父目錄的文件夾下會生成以ip開頭的文件File file=new File(parentFile,ip+"("+count+").jpg");if(file.exists()){//如果該文件已存在,則讓count先自增后加創建file=new File(parentFile,ip+"("+ ++count +").jpg");}//獲取輸入流中的數據,然后將數據寫入到File對象中FileOutputStream fos = new FileOutputStream(file);//客戶端傳遞過來的數據也要進行讀寫操作byte[] buf=new byte[1024];//定義一個讀取的長度int len=0;while((len=in.read(buf))!=-1){fos.write(buf,0,len);}//如果文件上傳完成,則提示客戶 文件上傳成功!OutputStream out = socket.getOutputStream();out.write("上傳成功".getBytes());//關流fos.close();socket.close();} catch (IOException e) {e.printStackTrace();}} }文件操作的服務端
每發現有客戶端來連接,直接啟動一個線程來和服務端通信
//文件上傳操作的服務端 public class FileServer {public static void main(String[] args) throws IOException {//創建ServerSocket對象ServerSocket serverSocket=new ServerSocket(10001);//accept()對象while(true){//此時這個socket包含了客戶端所有的信息Socket socket= serverSocket.accept();//創建對應的線程,獨立處理與客戶端的通信ServerThread serverThread=new ServerThread(socket);//啟動當前的線程來處理和客戶端對應的通信new Thread(serverThread).start();}} }客戶端
//文件上傳操作的客戶端類 public class FileClient {public static void main(String[] args) throws IOException {System.out.print("請輸入上傳問件對應的路徑");Scanner input=new Scanner(System.in);// 加入客戶端輸入 D:/work/1.jpgString upload=input.nextLine();//Socket要連接的服務器ip地址和端口號Socket socket=new Socket("localhost",10001);//獲取Socket的輸出流對象OutputStream out = socket.getOutputStream();//判斷upload是否真實存在if(!upload.isEmpty()){//文件不為空FileInputStream fis=new FileInputStream(upload);//定義一個字節數組byte[] buf=new byte[1024];int len=0;while((len=fis.read(buf))!=-1){//將buf中的數據轉移到out中out.write(buf,0,len);}//注意:當客戶端輸出數據完畢后,一定要進行關閉/*shutdown方法關流只是對當前socket持有的output流關掉,不會影響后續socket調其他流close會關掉所有與該對象相關的流*/socket.shutdownOutput();//處理服務端響應回來的數據(上傳成功!)InputStream in = socket.getInputStream();byte[] msg=new byte[1024];//調用read()int num=in.read(msg);//字節數組轉化成字符串進行輸出String str=new String(msg,0,num);System.out.println(str);fis.close();socket.close();}} }這樣我們就可以完成一個文件的傳輸啦!
總結
以上是生活随笔為你收集整理的JavaIO流实现文件传输的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 3628、验证回文串
- 下一篇: 二手iPhone手机选购指南,花小钱办大