试图在java中向现有文件追加新行中的文本?

oyjwcjzk  于 2021-07-11  发布在  Java
关注(0)|答案(2)|浏览(202)

如何在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
        }
agxfikkp

agxfikkp1#

如果要移到下一行,必须在str变量中使用新行字符。

String str = "\n" + sc.nextLine();

你也应该把它放在输入之前,因为你会把它附加在文件的末尾。

pgx2nnw8

pgx2nnw82#

使用system.lineseparator()常量,该常量在运行时应用并与所有操作系统兼容。

Files.write(Paths.get("C:\\Users\\souravpal\\Documents\\Bandicam\\buddy.txt"),
                    (System.lineSeparator() + str).getBytes(),StandardOpenOption.APPEND);

相关问题