是否可以对 java 套接字中的文件进行这两种操作?如果有怎么办?我尝试了一种方法,其中客户端发送一个令牌,例如“R”用于读取,“W”用于写入,服务器对其进行检查并执行请求的操作。但这似乎不起作用。
一段相关的客户端代码如下:
public static void readFile(String input, BufferedReader stdin, PrintWriter out, BufferedReader in) throws IOException
{
System.out.println("Enter the filename that you want to read");
stdin = new BufferedReader(new InputStreamReader(System.in));
String input = stdin.readLine();
out.println("R" + input);
System.out.println("File from server \n\n" + in.readLine());
}
public static void writeFile(String input, BufferedReader stdin, PrintWriter out, BufferedReader in, Socket s) throws IOException
{
System.out.println("Enter the filename that you want to write to");
stdin = new BufferedReader(new InputStreamReader(System.in));
input = stdin.readLine();
out.println("W" + " " + input);
System.out.println("Enter the text you want to enter in the file");
out.println(stdin.readLine());
System.out.println("File has been updated. The updated file from the server is: " + in.readLine());
}
在服务器端,我编写了如下代码:
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
String[] recv = in.readLine().split(" ");
String file_name = recv[1];
这是我检查是否应该读取或写入文件的地方:
if(recv[0] == "R")
{
while((file_name = recv[1]) != null)
{
System.out.println("Filename got from client: " + file_name);
fileread = new BufferedReader(new FileReader(file_name));
while((line = fileread.readLine()) != null)
{
out.println(line);
}
System.out.println("The contents of the file " + file_name + " has been sent to the client");
}
}
if(recv[0] == "W")
{
System.out.println("Filename got from client: " + file_name);
File file = new File(file_name);
filewrite = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(filewrite);
line = in.readLine();
System.out.println(line);
bw.write(line);
bw.close();
out.println(line);
System.out.println("The contents of the file " + file_name + " has been sent to the client");
}
}
我没有得到明确的错误,但是当我运行程序时,客户端获取文件名,服务器识别它(我知道这一点,因为我让服务器打印文件名),然后服务器什么也不做;它停止(没有任何错误或异常)。
谁能告诉我哪里出错了?还是有更好的方法来执行任务?
提前致谢。