我有一个客户端和服务器,在客户端输入文件名,该文件名将在服务器端在预定义路径下检查,如果文件存在,它将在类似的预定义路径下传输到客户端。我有两个问题:
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();
}
}
}