目标:服务器从客户端发送的文本文件中读取数据。服务器将此数据存储在另一个文本文件中。
问题:我能够读入文本文件并将其打印到控制台,但是,当我使用BufferedWriter运行我的代码并打开新的文本文件后,文件为空。我不完全确定我是否错误地使用了BufferedWriter函数,或者我是否缺少任何关键函数?
代码:
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
while (true) {
fromUser = stdIn.readLine();
if (fromUser != null) {
FileReader file = new FileReader("client-temp.txt");
BufferedReader tc = new BufferedReader(file);
BufferedWriter bw = new BufferedWriter(new FileWriter("datastore.txt"));
String line;
while ((line = tc.readLine()) != null)
{
String[] data = line.split(",");
String sensortype = data[0];
String date = data[1];
String time = data[2];
String reading = data[3];
String newdata = sensortype + date + time + reading;
System.out.println(line);
if (line != null)
{
out.write(line);
out.flush();
}
System.out.println("Data sent to file");
}
System.out.println(EmsClientID + " sending " + fromUser + " to EmsServer");
out.println(fromUser);
}
fromServer = in.readLine();
System.out.println(EmsClientID + " received " + fromServer + " from EmsServer");
}
答案 0 :(得分:0)
您的代码不完整。我会在这里一时兴起并假设你的问题。
添加
out.close();
代码末尾。
答案 1 :(得分:0)
您永远不会在flush
的实例上调用close
或BufferedWriter
,事实上,您完全忽略它。此外,您的资源管理不存在。如果您打开资源,则应将其关闭。
例如......
FileReader file = new FileReader("client-temp.txt");
try (BufferedReader tc = new BufferedReader(file)) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("datastore.txt"))) {
String line;
while ((line = tc.readLine()) != null)
{
String[] data = line.split(",");
String sensortype = data[0];
String date = data[1];
String time = data[2];
String reading = data[3];
String newdata = sensortype + date + time + reading;
System.out.println(line);
if (line != null)
{
bw.write(line);
bw.newLine();
}
System.out.println("Data sent to file");
}
} catch (IOException exp) {
exp.printStackTrace();
}
} catch (IOException exp) {
exp.printStackTrace();
}
有关详细信息,请参阅The try-with-resources Statement
( ps:您可以复合try-with-resource
语句,在同一try (...) {
部分中打开多个资源,但我想演示基本概念)