[英]Why CopyOnWriteArrayList needs copies for both write and read operations?
[英]Is it possible for a server side socket to do both read and write operations on files?
是否可以对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");
}
}
我没有得到明确的错误,但是当我运行程序时,客户端获取文件名,服务器识别出该文件名(我知道这是因为我使服务器打印文件名),然后服务器不执行任何操作。 它停止(没有任何错误或异常)。
谁能告诉我我哪里出问题了? 还是有更好的方法来执行任务?
提前致谢。
这是Java中常见的noobie错误:
recv[0] == "R"
以上称为引用比较 ,不比较实际的字符串值,而是对对象的引用。
假设recv[0]
的内容为“ R”,则recv[0] == "R"
最有可能返回false
进行字符串比较的正确方法是
recv[0].equals("R")
如果您想忽略字符大小写
recv[0].equalsIgnoreCase("R")
在代码中,由于您正在使用readLine()
读取文件,因此还必须确保文件以换行符结尾。 如果没有,则readLine()
方法将继续等待。 后续语句将不会执行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.