Socket如何传送多个文件??
我写了一个传送多个文件的程序,可结果却是把多个文件都写在一个文件里去了,请问如何把文件分开来写入??主要代码如下:
server:
程序代码:
public void run() { try { // get out and in stream DataOutputStream dout = new DataOutputStream(s.getOutputStream()); DataInputStream din = new DataInputStream(s.getInputStream()); dout.writeUTF("{FileList}" + fileList); FileInputStream fis; DataInputStream dataIn; int length = 0; ta.append(din.readUTF() + "\n"); state = "send"; // send file one by one for(File f : fileList) { dout.writeUTF("{FileBegin}" + f); fis = new FileInputStream(f); dataIn = new DataInputStream(fis); byte[] buffer = new byte[1024];// 定义一byte类型的缓冲区 // send buffer length once ta.append("File: " + f + " send begin!\n"); while ((length = dataIn.read(buffer)) != -1) { dout.write(buffer, 0, length); } ta.append("File: " + f + " send end!\n"); dout.flush(); fis.close(); dataIn.close(); } din.close(); dout.close(); s.close(); state = "rest"; } catch(Exception exc) { exc.printStackTrace(); } }client:
程序代码:
public void receiveFile() { state="receive"; try { dout.writeUTF("{ReceiveFiles}"); // receive each file through one new socket for(int i=0; i<list.length; i++) { // read file name String str = din.readUTF(); int j=str.lastIndexOf("\\"); // create file output File f = new File(path.getPath() + "\\" + str.substring(j+1)); if(!f.exists()) f.createNewFile(); FileOutputStream fos = new FileOutputStream(f); int length=0; byte[] buffer = new byte[1024]; // read file buffer and write it into file f ta.append("File: " + f + " receive begin!\n"); while ((length = din.read(buffer)) != -1) { fos.write(buffer, 0, length); } fos.close(); ta.append("File: " + f + " receive end!\n"); } din.close(); socket.close(); } catch(Exception e) { e.printStackTrace(); } state="rest"; }