使用分隔符读取文件并按顺序输出

时间:2016-03-18 10:36:58

标签: java

我在下面有以下文件fruit.txt,我想在文件中读取并按顺序输出它们。

我做了什么,是我尝试使用嵌套for循环来获取列表,但我失败了。 我不确定如何在循环中添加更多记录。

BufferedReader brInput = new BufferedReader(new FileReader("fruit.txt"));
String line;
String x = null;
while ((line = brInput.readLine()) != null) {
   String[] fruit = line.split("\\.");

    for(int i =0; i<fruit.length;i++){
        for(int j =0; j<fruit.length;j++){
             x = fruit[i]+"."+fruit[j];
            System.out.println(x);
        }
    }
}

当前输出:

apple.apple
apple.orange
apple.pear
apple.grape
orange.apple

fruit.txt:

apple.orange.pear.grape
apple.orange.pear.grape.melon
apple.orange.pear.grape.melon.Apricot
banana.berry.Avocado

预期产出:

apple
apple.orange
apple.orange.pear
apple.orange.pear.grape

apple
apple.orange
apple.orange.pear
apple.orange.pear.grape
apple.orange.pear.grape.melon

apple
apple.orange
apple.orange.pear
apple.orange.pear.grape
apple.orange.pear.grape.melon
apple.orange.pear.grape.melon.Apricot

banana
banana.berry
banana.berry.Avocado

3 个答案:

答案 0 :(得分:3)

您目前正在做的是将每个数组元素与每个数组元素(甚至是相同的元素)组合在一起。看起来你想在每次迭代中添加一个数组元素,因此你应该这样做:

StringBuilder sb = new StringBuilder();
for( String word : fruit) {
  //if there's already something in the StringBuilder add a dot before adding the word
  if( sb.length() > 0 ) {
    sb.append( "." );
  }

  sb.append( word );
  System.out.println( sb.toString() );
}

假设fruit数组为{"apple","orange","pear","grape"},则输出

apple
apple.orange
apple.orange.pear    
apple.orange.pear.grape

答案 1 :(得分:0)

您只需迭代String数组一次。将第一个值分配给String x,然后将数组中的每个后续项目追加到x。您可以修改for循环,如下所示:

for(int i = 0; i < fruit.length; i++) {
  if(i == 0) {
    x = fruit[i];
  } else {
    x += "." + fruit[i];
  }
  System.out.println(x);
}

答案 2 :(得分:0)

使用下面的代码与扫描仪库,这将完美地工作直到结束:

File f=new File("C:/Users/User1/Desktop/t.txt");

            Scanner s=new Scanner(f);
            s.useDelimiter("\r\n");
            String d=null;
            String temp=null;
            String da[]=null;

            int i=0;

            d=s.nextLine();

            while(s.hasNextLine()){                 
                d=d.replace(".", ",");
                da=null;
                da=d.split(",");

                temp=null;
                i=0;

                while(i<da.length){
                    if(i==0){
                        temp=da[i];
                    }
                    else{
                temp=temp+"."+da[i];    

                    }

JOptionPane.showMessageDialog(null,temp);  //-----------Output-------------
                i++;
                }                   
                d=null;
                d=s.nextLine();
                }   
            s.close();