扫描仪是否抑制换行符(in)?

Does Scanner suppress linefeed characters (i.e. \n)?

我注意到 Scanner 如何忽略换行符,例如 \n 代表换行符或 \" 代表字符串内双引号,这似乎有点必要,所以我想知道是否有什么我可以我做错了,或者扫描仪确实忽略了换行?

这是代码示例,其中注释的 String text = "This \n Must \n Work!!" 有换行功能并会输出

This
Must
Work!!

但是,如果我们使用 String text = sc.nextLine();
类型 "This \n Wont \n Work" 它不会创建一个新行而只会输出

This \n Wont \n Work

到test.txt

代码示例:


import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

public class StoringTheString {

    public static void main(String[] args) {
        try {
            Scanner sc = new Scanner(System.in);
            System.out.println("Type anything: ");
            String text = sc.nextLine();
            // String text = "This \n Must \n Work!!!" ;
            sc.close();
            PrintWriter out = new PrintWriter("test.txt");
            out.println(text);
            out.close();
        }catch (FileNotFoundException e) {
            e.printStackTrace();

        }

    }
}


对不起,如果我的post不清楚,请评论,如果有一些误解,我会尽量详细说明。
谢谢你的时间^.. .^

试试这个:

String text = "This "+  "\r\n"+ "Must"+ "\r\n"+ "Work!!!" +"\r\n";

如果不行,更改out.println(文本);到 out.print(文本);

尝试使用扫描仪从键盘获取输入,然后使用另一个扫描仪将输入分成单独的行。

public static void main(String[] args) throws Exception {
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Type anything: ");
    String text = keyboard.nextLine();

    Scanner scanner = new Scanner(text);
    // This is what will break the line apart
    scanner.useDelimiter("\s?\\n\s?");

    while (scanner.hasNext()) {
        System.out.println(scanner.next());
    }
}

结果:

Type anything: This \n Must \n Work!!!
This
Must
Work!!!