2013-04-02 42 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

相关问题