我有一個客戶端和服務器,其中在客戶端輸入文件名,該文件名將在服務器端檢查預定義的路徑下,如果文件存在,它將被傳輸以類似的預定義路徑向客戶端發送。我有兩個問題:使用java套接字從服務器到客戶端的文件傳輸。錯誤在服務器端和文件傳輸到客戶端是空的
1)在服務器,我無法比較文件在給定的預定義路徑,因爲它顯示FileNotFoundException(沒有這樣的文件/目錄)。
2)即使出現上述例外情況,文件也會被傳輸並且是空的。
這裏是我的客戶端和服務器:
客戶:
import java.io.*;
import java.net.*;
import java.util.*;
public class ft2client
{
public static void main(String srgs[])throws IOException
{
Socket s=null;
BufferedReader get=null;
PrintWriter put=null;
try
{
s=new Socket("127.0.0.1",8085);
get=new BufferedReader(new InputStreamReader(s.getInputStream()));
put=new PrintWriter(s.getOutputStream(),true);
}
catch(Exception e)
{
System.exit(0);
}
String u,f;
System.out.println("Enter the file name to transfer from server:");
DataInputStream dis=new DataInputStream(System.in);
f=dis.readLine();
put.println(f);
File f1=new File(f);
String str = "/home/user/";
FileOutputStream fs=new FileOutputStream(new File(str,f1.toString()));
while((u=get.readLine())!=null)
{
byte jj[]=u.getBytes();
fs.write(jj);
}
fs.close();
System.out.println("File received");
s.close();
}
}
服務器:
import java.io.*;
import java.net.*;
import java.util.*;
public class ft2server
{
public static void main(String args[])throws IOException
{
ServerSocket ss=null;
try
{
ss=new ServerSocket(8085);
}
catch(IOException e)
{
System.out.println("couldn't listen");
System.exit(0);
}
Socket cs=null;
try
{
cs=ss.accept();
System.out.println("Connection established"+cs);
}
catch(Exception e)
{
System.out.println("Accept failed");
System.exit(1);
}
PrintWriter put=new PrintWriter(cs.getOutputStream(),true);
BufferedReader st=new BufferedReader(new InputStreamReader(cs.getInputStream()));
String s=st.readLine();
String str = "/home/user/Desktop/";
String path = str + s;
System.out.println("The requested file is path: "+path);
System.out.println("The requested file is : "+s);
File f=new File(path);
if(f.exists())
{
BufferedReader d=new BufferedReader(new FileReader(s));
String line;
while((line=d.readLine())!=null)
{
put.write(line);
put.flush();
}
d.close();
System.out.println("File transfered");
cs.close();
ss.close();
}
}
}
嗨,謝謝,但是當我傳輸一個zip文件時,傳輸的文件大小更多,並且當我嘗試打開它時顯示以下錯誤:_存檔:/home/user/herb_2.5.7-Stable-Full_Package.zip 13175984 6008 警告[/home/user/herb_2.5.7-Stable-Full_Package.zip]:571117285額外的字節在開始處或zipfile內(無論如何嘗試處理)錯誤[/home/user/herb_2.5.7-Stable-Full_Package.zip]:找不到中心目錄的開始; zipfile損壞(請檢查您是否已經在適當的BINARY模式下傳輸或創建了zip文件,並且您已編譯解壓縮正確)_ – highlander141