如何拆分文件中的字符串并读取它们?

Sol*_*oli 8 java split filereader

我有一个包含信息的文件.看起来像:

    Michael 19 180 Miami
    George 25 176 Washington
    William 43 188 Seattle
Run Code Online (Sandbox Code Playgroud)

我想分割线条和字符串并阅读它们.我希望它看起来像:

    Michael
    19
    180
    Miami
    George
    ...
Run Code Online (Sandbox Code Playgroud)

我使用了这样的代码:

    BufferedReader in = null;
    String read;
    int linenum;
    try{
        in = new BufferedReader(new FileReader("fileeditor.txt")); 
    }
    catch (FileNotFoundException e) {System.out.println("There was a problem: " + e);}
    try{
        for (linenum = 0; linenum<100; linenum++){
            read = in.readLine();
            if(read == null){} 
            else{
                String[] splited = read.split("\\s+");
                System.out.println(splited[linenum]);
           }
       }
    }
    catch (IOException e) {System.out.println("There was a problem: " + e);} 
}
Run Code Online (Sandbox Code Playgroud)

这给了我什么

    Michael
    25
    188
Run Code Online (Sandbox Code Playgroud)

我认为它可能是我的for循环的一个问题,但我在编程方面不是很先进,我会很感激帮助.谢谢.

Mad*_*mer 7

你在那里很有意义.

当读取文件时,Reader它将null在到达流的末尾时返回,这意味着没有其他内容可供读取.您当前的方法意味着您想要读取至少100行,但不会更多......如果您的文件大小增加,这将在将来成为问题...它也有点浪费

相反,我们应该使用一个null值来表示文件末尾的事实.

拆分线时,它将包含许多元素.您正在使用该linenum变量来打印这些变量.问题是,你已经读过并拆分了这行,这linenum与这个任务无关,因为它代表你已经读过的行数,而不是你刚刚拆分的字符串部分.

相反,您需要使用内部循环来显示每行的各个拆分元素......

例如...

BufferedReader in = null;
try {
    in = new BufferedReader(new FileReader("fileeditor.txt"));
    String read = null;
    while ((read = in.readLine()) != null) {
        String[] splited = read.split("\\s+");
        for (String part : splited) {
            System.out.println(part);
        }
    }
} catch (IOException e) {
    System.out.println("There was a problem: " + e);
    e.printStackTrace();
} finally {
    try {
        in.close();
    } catch (Exception e) {
    }
}
Run Code Online (Sandbox Code Playgroud)

另外,不要忘记,如果你打开它,你必须关闭它;)

您可能还需要花一点时间来完成基本I/O ;)