我有一个用java编写的服务器,它监听特定的端口号。我还有一个Objective-C客户端连接到这个服务器并进行通信。沟通很好。现在,我必须从终端获取objective-c客户端的输出并输入由java服务器创建的文件。我该怎么做呢?普通的FileWriter函数似乎不起作用。以下是我所拥有的服务器的一部分。
// Get the client message
while((inputLine = bufferedReader.readLine()) != null) {
System.out.println(inputLine);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//read a line from the console
String lineFromInput = in.readLine();
File file = new File("./user_statistics.txt");
if(!file.exists()){
file.createNewFile();
}
//create an print writer for writing to a file
fileWriter = new FileWriter(file);
//output to the file a line
fileWriter.write(lineFromInput);
}
//close the file
fileWriter.close();
serverSocket.close();
答案 0 :(得分:0)
首先从客户端读取一行(到目前为止一直很好),然后从控制台获取输入并尝试将其写入文件。您应该删除控制台内容并从inputLine
读取:
// Get the client message
while((inputLine = bufferedReader.readLine()) != null) {
System.out.println(inputLine);
//read a line from the console
File file = new File("./user_statistics.txt");
if(!file.exists()){
file.createNewFile();
}
//create an print writer for writing to a file
fileWriter = new FileWriter(file);
//output to the file a line
fileWriter.write(inputLine);
}
//close the file
fileWriter.close();
serverSocket.close();
顺便说一下:如果您关心效果,则应使用.read(char[] cbuf, int off, int len)
的{{1}}方法,而不是bufferedReader
。你完成它的方式,将浪费时间: