0
我有以下代碼上傳文件從客戶端到服務器TCP,但是當我嘗試打開手動文件是空的爲什麼好的重量.. 我看了很多帖子stackOverflow但沒有任何改變 THX (對不起我的英文不好)
服務器:BufferedOuputStream使空白文件
ThreadServer擴展公共Thread類{
private Socket soc;
private FileOutputStream fos;
private BufferedOutputStream bos;
private InputStream in;
public ThreadServer (Socket soc) {
this.soc = soc;
}
public void run(){
try {
fos = new FileOutputStream("C:/Users/erwan/workspace/Word/server/text.txt");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
bos = new BufferedOutputStream(fos);
byte[] buffer = new byte[1024];
try {
in = soc.getInputStream();
int count = 0;
while((count= in.read(buffer, 0 , buffer.length)) != -1) {
System.out.println(count+" octets received...");
bos.write(buffer);
}
bos.flush();
bos.close();
in.close();
soc.close();
System.out.println("File sent succesfully!");
}catch(IOException e){
e.printStackTrace();
System.out.println("Une erreur est survenu");
}
}
}
客戶端:
public class Client {
private static Socket as;
private static FileInputStream fis;
private static BufferedInputStream bis;
private static OutputStream out;
public static void main(String[] args){
as = null;
try{
as = new Socket(InetAddress.getLocalHost(),4020);
File f = new File (args[0]);
byte [] buffer = new byte [(int) f.length()];
fis = new FileInputStream(f);
setBis(new BufferedInputStream(fis));
out = as.getOutputStream();
System.out.println("uploading...");
out.write(buffer,0,buffer.length);
out.flush();
out.close();
System.out.println("the file is uploaded.");
as.close();
}catch(IOException e){
e.printStackTrace();
}
}
我真的不明白爲什麼fis.read(buffer,0,buffer.lenght)解決了這個問題,但真的非常感謝你回答:)如果你能再次解釋我的dos是如何工作的? thx –
是的。這並不複雜。你做了一個新的字節[(int)f.length()]。所做的是分配一個存儲區域來存儲f.length()字節。它不會將任何數據放入這些內存字節中。在大多數情況下,數組將被jvm初始化爲0個字節(二進制零,因此經常在編輯器中顯示爲奇怪的字符)。爲了將您的輸入文件中的數據動態地放入新創建的數組中,您需要執行fis.read。 –