Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
试图在Java中向现有文件追加新行中的文本?_Java_String_File_Io - Fatal编程技术网

试图在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上工作?请查看以下内容: