文件编写器定界符问题在扫描第一行后抛出异常

File Writer Delimiter Problem throws an Exception after scanning 1st line

所以我在这里遇到了这个问题我正在尝试使用定界符“,”这样我就可以做到 使用 space 并且它不会将 space 识别为分隔符

public class Test2 {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        File file = new File("Project.txt");
        Scanner reader2 = new Scanner(file);
        reader2.useDelimiter(",");
        String wholeFile = "";
        String ID = "";
        String Name = "";
        String Birthday = "";
        String Gender = "";
        String Age = "";
        String CNumber = "";
        while(reader2.hasNext())
        {
            ID = reader2.next();
            Name = reader2.next();
            Birthday = reader2.next();
            Gender = reader2.next();
            Age = reader2.next();
            CNumber = reader2.next();
            wholeFile = wholeFile+(ID+" "+Name+" "+Birthday+" "+Gender+" "+Age+" "+CNumber+"\n");
        }
        JOptionPane.showMessageDialog(null, wholeFile);
        
        JFrame frame= new JFrame();
        frame.setSize(500,500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        JPanel panel = new JPanel();
        panel.setLayout(null);
        frame.add(panel);
        
        JTextArea tf = new JTextArea(wholeFile);
        tf.setBounds(30, 30, 400, 400);
        panel.add(tf);
        frame.setVisible(true);
    
    }

} 

和文件“Project.txt”

1,Ron,September,Male,19,09567369293
2,Ron,September,Male,19,09567369293

问题是它在第一行完美运行,但在下一行会抛出异常

Exception in thread "main" java.util.NoSuchElementException
    at java.base/java.util.Scanner.throwFor(Scanner.java:937)
    at java.base/java.util.Scanner.next(Scanner.java:1478)
    at Test2.main(Test2.java:32)

如果我使用 space " " 作为分隔符,它也可以正常工作...请帮助我如何使用它 分隔符“,”而不是“”,即使我认为它应该可以正常工作,它也不会抛出异常。

我使用 JOptionPane 和 GUI 只是为了比较所以请不要介意,应该与我的问题无关

问题是CNumber和ID合并起来算作一个。因为您没有在定界符模式中定义 \n

更改如下,

reader2.useDelimiter(",|\n");