How to append text to an existing file in Java?
我正在使用解决方案中提到的方法,并且我正在接受用户输入。但正文后面是最后一个词。有没有办法在那里添加一个新的行?
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
}发布于 2020-11-21 16:13:52
如果要移动到下一行,则必须在str变量中使用换行符\n。
String str = "\n" + sc.nextLine();你也应该把它放在输入之前,因为你会把它追加到文件的末尾。
发布于 2020-11-21 16:32:51
使用在运行时应用并与所有操作系统兼容的System.lineSeparator()常量。
Files.write(Paths.get("C:\\Users\\souravpal\\Documents\\Bandicam\\buddy.txt"),
(System.lineSeparator() + str).getBytes(),StandardOpenOption.APPEND);https://stackoverflow.com/questions/64940958
复制相似问题