2013-04-02 44 views
0

我有一個完美的方法,但它不是寫入文件,而是如何將文件的每一行添加到列表中? (有些文件的.docx,有些是.TXT)如何將文件通過套接字保存到列表中

private static void saveMultiple(Socket socket) { 
    try { 
     BufferedInputStream bis = new BufferedInputStream(socket.getInputStream()); 
     DataInputStream dis = new DataInputStream(bis); 
     int filesCount = dis.readInt(); 
     File[] files = new File[filesCount]; 
     for (int i = 0; i < filesCount; i++) { 
      long fileLength = dis.readLong(); 
      String fileName = dis.readUTF(); 
      files[i] = new File("/Users/.../Desktop/Data/" + fileName); 
      FileOutputStream fos = new FileOutputStream(files[i]); 
      BufferedOutputStream bos = new BufferedOutputStream(fos); 
      for (int x = 0; x < fileLength; x++) { 
       bos.write(bis.read()); 
      } 
      bos.close(); 
     } 
     dis.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 
+0

定義「一條線」。二進制文件不可能有任何行 – MadProgrammer

+0

如果您不想在文件系統中寫入文件,則不能包含它們的列表。但是你可以有一個我猜測的字節數組列表.. – Thihara

回答

0

你這部分代碼:

bos.write(bis.read()); 

基本上讀取插座1個字節,並將其寫入文件。現在不用這樣做了,您可以將字節緩衝到一個字節數組中,並使用java.util.String String(byte[] bytes)構造函數將其轉換爲字符串。考慮使用ByteInputStream.read(byte[] b, int off, int len)方法。

您還必須考慮到字符編碼和內存消耗。

+0

謝謝你我會試試這個 – CBennett

相關問題