テンプレート ファイルの最後に到達すると、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()));
//}
}
解決策は、ファイルを閉じてから再度開く (まったく良くない) か、2 つを分離することです。最初にテンプレートを 1 行ずつリストに読み取り、次にリスト全体を反復処理します。
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();