0

是否可以对 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");

    }
}

我没有得到明确的错误,但是当我运行程序时,客户端获取文件名,服务器识别它(我知道这一点,因为我让服务器打印文件名),然后服务器什么也不做;它停止(没有任何错误或异常)。

谁能告诉我哪里出错了?还是有更好的方法来执行任务?

提前致谢。

4

1 回答 1

0

这是java中一个常见的noobie错误:

recv[0] == "R"

以上称为引用比较,不比较实际的字符串值,而是对对象的引用。

假设内容recv[0]是“R”,recv[0] == "R"很可能会返回 false

进行字符串比较的正确方法是

recv[0].equals("R")

如果你想忽略字符大小写

recv[0].equalsIgnoreCase("R")

在您的代码中,由于您正在使用 读取文件readLine(),因此您还必须确保文件以换行符结尾。如果没有,该readLine()方法将继续等待。不会执行后续语句

于 2013-09-17T02:19:18.740 回答