我这里有一个代码,我将用它作为Java Server中的日志记录。 这似乎在单行输入中工作正常。但是当我进入多行时。例如:
Hey there!
Hey More!
当我查看PrintWriter创建的文本文件时,它会显示我:
Hey there!Hey More!
我想在文本文件中看到的是:
Hey there!
Hey More!
这是我的代码:我不知道如何追加它。我在考虑\ n但是这不起作用。或者我的代码中缺少某些内容。请检查,你会对我很有帮助!谢谢!
try
{
clientSocket = serverSocket.accept(); // accept the client connection
inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader); // get the client message
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
StringBuilder str =new StringBuilder();
StringBuilder abc =new StringBuilder();
while ((message = bufferedReader.readLine()) != null)
{
abc.append("Message from " + message + " at " + dateFormat.format(cal.getTime())+"/n");
System.out.println("Message from " + message + " at " + dateFormat.format(cal.getTime()));
str.append(message+"\n");
}
PrintWriter out= new PrintWriter(new BufferedWriter(new FileWriter("C:/god.txt", true)));
out.println(abc);
out.close ();
JOptionPane.showMessageDialog(null, str);
inputStreamReader.close();
clientSocket.close();
} catch (IOException ex)
{
System.out.println("Problem in message reading");
}
答案 0 :(得分:2)
BufferedWriter
有一个newLine方法。你应该使用相同的
String line = new String();
BufferedWriter writer= nnew BufferedWriter(new FileWriter("C:/god.txt", true));
while ((message = bufferedReader.readLine()) != null)
{
line = "Message from " + message + " at " + dateFormat.format(cal.getTime());
System.out.println("Message from " + message + " at " + dateFormat.format(cal.getTime()));
writer.write(line);
writer.newLine();
}
PrintWriter out= new PrintWriter(writer);
答案 1 :(得分:1)
您可以从以下位置获取与系统无关的行分隔符:
System.getProperty("line.separator");
或者在Java 1.7中:
System.lineSeparator();
在您的代码中用以上其中一个替换所有“\ n”。
另外一点:正如其他人所说,考虑使用日志框架。