具有数组列表的I / O.

时间:2017-04-21 13:00:40

标签: java string arraylist

我只是想知道是否有办法循环文本文件,直到找到特定的字符串。 例如,假设您有一个文本文件,其中包含以下内容:

香蕉

苹果

葡萄

甜瓜

樱桃

草莓巧克力香草

我基本上想要编写一个循环输入文件的程序,直到它到达用户指定的特定字符串,然后将下一行存储在数组列表中。所以,基本上说如果我把樱桃推到我想要它将草莓,巧克力,香草存放在阵列列表中。对于我的生活,我无法弄清楚如何做到这一点,所以任何事情都会受到赞赏。我到目前为止的内容如下。

public static void main(String[] args) throws IOException {
        String line;
        ArrayList<String> names = new ArrayList<>();
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the input file: ");
        String input = in.next();
        FileReader file = new FileReader(input);

        BufferedReader reader = new BufferedReader(file);

        System.out.print("What fruit do you want: ");
        String fruit = in.next();
        line = reader.readLine();


        while ((line != null)) {
            if(line.equals(fruit){
          }
            }

5 个答案:

答案 0 :(得分:1)

只需循环输入,直到遇到搜索到的行,并将之后找到的每一行存储在列表中。

    String line;

    while((line = reader.readLine()) != null)
        if(line.equals(fruit))
            break;

    ArrayList<String> lines = new ArrayList<>();
    while((line = reader.readLine()) != null)
        lines.add(line);

答案 1 :(得分:1)

如果我理解你的问题,我知道你可以从

开始
filters

现在你可以做什么

Scanner scanner = new Scanner(file);
List<String> list = new ArrayList<String>();
while (scanner.hasNextLine()) { // read the entire file into list but it consumes time especially if the file is big (not perfect choice)
  list.add(scanner.nextLine());
}

答案 2 :(得分:0)

您可以使用boolean来指示何时找到该值,何时为真,您可以在列表中添加该行:

 boolean isFound = false;
 String line;
 while ((line=reader.readLine())!= null) {
       if(!isFound && line.equals(fruit){
         isFound = true;
       }
       else if (isFound){
         names.add(line);
       }
 }

答案 3 :(得分:0)

创建标志isFound。找到字符串时将其设置为true。 然后它会在下一个循环中处理并像这样设置为false。

bool isFound=false;       
while ((line != null)) {
          if(isFound==true){
              names.add(string)
              isFound=false;
          }
            if(line.equals(fruit){
              isFound=true;
          }
            }

答案 4 :(得分:0)

检查出来:

public static void main(String[] args) throws IOException {
    String line;
    List<String> names = new ArrayList<>();
    Scanner in = new Scanner(System.in);
    System.out.print("Enter the input file: ");
    String input = in.next();
    FileReader file = new FileReader(input);

    BufferedReader reader = new BufferedReader(file);

    System.out.print("What fruit do you want: ");
    String fruit = in.next();

    boolean found=false;
    while ((line = reader.readLine()) != null){
        if (line.equals(fruit) || found) {
            names.add(line);
            found=true;
        }
    }
}