试图在Java中向现有文件追加新行中的文本?
我正在使用解决方案中提到的方法,并接受用户输入。 但是文本中附加了最后一个单词。有没有办法在那里增加一行试图在Java中向现有文件追加新行中的文本?,java,string,file,io,Java,String,File,Io,我正在使用解决方案中提到的方法,并接受用户输入。 但是文本中附加了最后一个单词。有没有办法在那里增加一行 Scanner sc= new Scanner(System.in); System.out.print("Enter a string: "); String str= sc.nextLine(); try { Files.write(Paths.get("C:\\Users\
Scanner sc= new Scanner(System.in);
System.out.print("Enter a string: ");
String str= sc.nextLine();
try {
Files.write(Paths.get("C:\\Users\\souravpal\\Documents\\Bandicam\\buddy.txt"), str.getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
如果要移动到下一行,必须在str变量中使用新行字符
String str = "\n" + sc.nextLine();
您还应该将它放在输入之前,因为您将在文件末尾追加它。使用System.lineSeparator()常量,该常量在运行时适用,并与所有操作系统兼容
Files.write(Paths.get("C:\\Users\\souravpal\\Documents\\Bandicam\\buddy.txt"),
(System.lineSeparator() + str).getBytes(),StandardOpenOption.APPEND);
应避免使用特定的新行分隔符,如“\n”或“\r\n”,这取决于操作系统。我在所有操作系统上都使用了\n,这是有效的。为什么您认为它只在windows上工作?请查看以下内容: