2016-09-09 36 views
0

与往常一样,我在使用Streams和套接字时遇到了问题。套接字中InputStream/OutputStream的奇怪行为

这里是我的代码:

客户

bitOut.write((f.getName() + "\n").getBytes()); 
//System.out.println(f.length()); // <- This is the odd part. 
bitOut.write((int) f.length()); 
bitOut.flush(); 

fileIn = new FileInputStream(f); 
byte buffer[] = new byte[BUFFER_SIZE]; 
int len; 
while ((len = fileIn.read(buffer)) != -1) { 
    bitOut.write(buffer, 0, len); 
} 
fileIn.close(); 

服务器

file = sc.nextLine(); 
int fileSize = bitIn.read(); // <- Here is my error! 
System.out.println(file + ", " + fileSize); 

fileOut = new FileOutputStream(folder + file); 
byte buffer[] = new byte[BUFFER_SIZE]; 
int len; 
while (fileSize > 0 && (len = bitIn.read(buffer)) != -1) { 
    fileOut.write(buffer, 0, len); 
    fileSize -= len; 
    System.out.println(fileSize); 
} 
fileOut.close(); 

如果我取消在客户端代码的System.out.println(f.length()),服务器始终得到正确的值在fileSize。但是如果我留下它的评论,fileSize往往是从f.length()后应发送的数据中的一个字节。一方面它很有趣,因为几乎只有当我在客户端打印出文件大小时,我才能在服务器上得到正确的结果。另一方面,我不知道如何解决它...

回答

0

好吧,我解决了它。它与Scanner有关,它的方法nextLine()吞下了我在文件名后发送的字节。现在我只使用正常的InputStreamOutputStream