1
    BufferedReader template = new BufferedReader(new FileReader("<InputFile>"));
    PrintWriter itemList = new PrintWriter(new FileWriter("<OutputFile>"));


    Iterator<String> iterator = allProduct.iterator();

    while(iterator.hasNext()){
        String l;
        while((l = template.readLine()) != null){
            if(l.contains("~")==false)
                itemList.print(l);                  
            else
                itemList.print(l.replace("~", iterator.next()));
        }

    }

    template.close();
    itemList.close();

但是编程并没有终止,也没有产生任何错误,它基本上被挂起。

4

1 回答 1

0

当您到达模板文件的末尾时,template.readLine()将继续返回null,因此您不会进入内部while循环,因此iterator不会前进。

您的代码将等同于:

while(iterator.hasNext()){
    String l;
    // This bit commented out because template.readLine() always returns null
    //while((l = template.readLine()) != null){
    //    if(l.contains("~")==false)
    //        itemList.print(l);                  
    //    else
    //        itemList.print(l.replace("~", iterator.next()));
    //}

}

解决方案是关闭然后重新打开文件(一点都不好)或将两者分开:首先将模板逐行读取到列表中,然后只遍历列表。

我只是猜测,但您可能不想iterator.next()每次遇到都打电话~,所以我认为您需要这样的东西:

BufferedReader template = new BufferedReader(new FileReader("<InputFile>"));
    ArrayList<String> templateLines = new ArrayList<String>(); //this is where we store the lines from the template
    String l;
    while((l = template.readLine()) != null){ //read template lines
        templateLines.add( l );  //add to list
    }
    template.close();  //done

    PrintWriter itemList = new PrintWriter(new FileWriter("<OutputFile>")); //now let's look at the output
    Iterator<String> iterator = allProduct.iterator();


    while(iterator.hasNext()){
        String product = iterator.next(); //take one product at a time
        for( String templateLine : templateLines ) { //for each line in the template
            if(templateLine.contains("~")==false) //replace ~ with the current product
                itemList.print(templateLine);                  
            else
                itemList.print(templateLine.replace("~", product));
        }

    }

    itemList.close();
于 2012-06-29T14:55:30.340 回答