2016-09-09 42 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