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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18607418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 09:28:31  来源:igfitidea点击:

How to split the strings in a file and read them?

javasplitfilereader

提问by Solijoli

I have a file with information in it. It looks like:

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

    Michael 19 180 Miami
    George 25 176 Washington
    William 43 188 Seattle

I want to split the lines and strings and read them. I want it to look like:

我想拆分行和字符串并阅读它们。我希望它看起来像:

    Michael
    19
    180
    Miami
    George
    ...

i used a code like this:

我使用了这样的代码:

    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);} 
}

What this gave me was

这给了我什么

    Michael
    25
    188

I think its probably an issue with my for loop but I'm not very advanced in programming and I'll appreciate help. Thanks.

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

采纳答案by MadProgrammer

You're part way there which is great.

你在那里的一部分,这很棒。

When reading a file, the Readerwill return nullwhen it reaches the end of the stream, meaning nothing else is available to be read. Your current approach means that you want to read at least 100 lines, but no more...this will become problematic in the future if you file size increases...it's also somewhat wasteful

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

Instead, we should use the fact a nullvalue indicates the end of the file..

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

When you split a line, it will contain a number of elements. You are using the linenumvariable to print these. The problem is, you've already read and split the line, the linenumis irrelevant for this task, as it represents the number of lines you've already read, not the part of the string you've just split.

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

Instead, you need to use a inner loop to display the individual split elements for each line...

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

For example...

例如...

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) {
    }
}

Also, don't forget, if you open it, you musty close it ;)

另外,不要忘记,如果你打开它,你会发霉关闭它;)

You might want to take a little more time going through Basic I/Oas well ;)

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

回答by Suresh Atta

 String[] splited = read.split("\s+");
  for (int i= 0; i<splited.length; i++){
  System.out.println(splited[i]);
  }

You should loop the result after you split the string.

您应该在拆分字符串后循环结果。

回答by Viktor Seifert

You can use a StreamTokenizer. It will split a stream into tokens according to its settings. From your question I think that you want to treat line endings just as token separators. The code would look like this:

您可以使用一个StreamTokenizer. 它将根据其设置将流拆分为令牌。根据您的问题,我认为您想将行尾视为标记分隔符。代码如下所示:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.StreamTokenizer;

public class ReaderSample {

    public static void main(String[] args) {
        BufferedReader in = null;
        try {
            in = new BufferedReader(new FileReader("fileeditor.txt"));
            StreamTokenizer st = new StreamTokenizer(in);
            st.eolIsSignificant(false);
            // remove comment handling
            st.slashSlashComments(false);
            st.slashStarComments(false);

            while(st.nextToken() != StreamTokenizer.TT_EOF) {
                if (st.ttype == StreamTokenizer.TT_NUMBER) {
                    // the default is to treat numbers differently than words
                    // also the numbers are doubles
                    System.out.println((int)st.nval);
                }
                else {
                    System.out.println(st.sval);
                }
            }
        }
        catch(IOException ex) {
            System.err.println(ex.getMessage());
        }
        finally {
            if (in != null) {
                try {
                    in.close();
                }
                catch (IOException ex) {
                }
            }
        }
    }
}

Depending on what you need to do woth the input you may need to set different options, the documentation should help you here.

根据您需要在输入中执行的操作,您可能需要设置不同的选项,文档应该可以帮助您。