繁体   English   中英

Java中的套接字通信后错误读取文件

[英]incorrect reading of file after socket communication in java

我有通过套接字从服务器发送到客户端的文件。 但是,当我尝试在客户端中获取前159个第一个字节时,所得到的结果要小于要求服务器读取原始文件中相同数量的结果,但是当我打印双方读取的长度时一样,但是一个几乎是另一个的2/3! 可能是什么问题呢? 我已经做了replaceAll("(\\\\r|\\\\n|\\\\s)","")以腾出任何空间或制表符,但仍然没有变化。 有什么建议么? 这是我编写文件的代码:

 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);
        }

在读取所需的所有数据之前,您需要循环:

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...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM