服务器端套接字是否可以对文件执行读写操作?

时间:2013-09-17 02:08:11

标签: java file sockets

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

    }
}

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

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

提前致谢。

1 个答案:

答案 0 :(得分:0)

这是java中常见的noobie错误:

recv[0] == "R"

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

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

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

recv[0].equals("R")

如果你想忽视字符大小写

recv[0].equalsIgnoreCase("R")

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