2013-08-20 37 views
2

我有这个文件,我通过套接字从服务器发送到客户端。但是,当我尝试重新启动客户端中的第159个第一个字节时,它会给出比当我要求服务器在原始文件中读取相同数量时更小的结果,但是当我打印两面读取的长度时它是一样的,但其中一个差不多是其他的三分之二!可能是什么问题呢?我已经让replaceAll("(\\r|\\n|\\s)","")脱离任何空间或制表,但仍然没有改变。 有什么建议吗? 这里是我写的文件中的代码:在java中套接字通信后文件读取不正确

FileOutputStream writer = new FileOutputStream("Splits.txt"); 
      String output= null; 
      StringBuilder sb2 = new StringBuilder(); 
      for (int i =0; i < MainClass.NUM_OF_SPLITS ; i++){ 
       StringBuilder sb1 = new StringBuilder(); 
        for (String s : MainClass.allSplits.get(i).blocks) 
        {sb2.append(s);} 
       sb1.append(sb2);} 
     output = sb2.toString().replaceAll("(\\r|\\n|\\s)", ""); 
     writer.write(output.getBytes(Charset.forName("ISO-8859-1"))); 
     writer.close(); 

在这里,我读文件:

FileInputStream fis = new FileInputStream("Splits.txt"); 
    InputStreamReader reader = new  InputStreamReader(fis,Charset.forName("ISO-8859-1")); 

for(int i = 0; i < splitsNum; i++) { 
     char[] buf = new char[159]; //param 
     int count = reader.read(buf); 
     String h=String.valueOf(buf, 0, count).replaceAll("(\\r|\\n||\\s)",""); 

     System.out.println(h); 
     } 
+0

为什么你认为整个数据将被读取到一个'read'的单个调用?你做了什么验证,文件本身已被正确传输? –

+0

我可以在客户端中手动打开客户端中的文件,我发现它在内容中与最初的文件相对应 – rima101

+0

不要手动打开文件。检查文件大小,理想情况下在两个文件上执行MD5哈希。 –

回答

0

您需要循环您已经阅读所有的数据,直到你需要:

char[] buf = new char[159]; 
int charsRead = 0; 
while (charsRead < buf.length) { 
    int count = reader.read(buf, charsRead, buf.length - charsRead); 
    if (count < 0) { 
     throw new EOFException(); 
    } 
    charsRead += count; 
} 
// Right, now you know you've actually read 159 characters... 
+0

它的工作原理。那么如果我想每次读取159个字符的文件,我该怎么办? – rima101

+0

@ rima101:每次要读取159个字符时使用该代码。 –

+0

当然你应该推荐使用DataInputStream.readFully()而不是手动编码? – EJP