【发布时间】:2014-09-02 07:48:23
【问题描述】:
问题:如何在一个集合中递增并使用 Java PrintWriter 写入 .TXT
总结:扫描指定文本文件并处理文本。然后将结果导出到报告 .txt。
这一切似乎都可以正常工作,直到我尝试使用 PrintWriter。 然后事情变得疯狂。如果一切都保持在代码中并且我打印到终端它可以工作。如果我使用 PrintWriter 它将创建文件,然后只打印 tType“text2”的第二次迭代。我从这里的帖子中尝试了许多不同的示例,但它们似乎都没有完全打印,根本不打印或出错。
文本文件输入示例:
123456 text1 175.00 001
234567 text2 195.00 001
345678 text1 175.00 007
456789 text3 160.00 005
987654 text4 90.00 006
876543 text3 160.00 007
765432 text2 195.00 011
需要的输出示例:
text1
text2
text3
text4
目前正在使用 PrintWriter 输出到 .txt
text2
代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
public class test {
public static void main(String[] arg){
Set<String> tSet= new TreeSet<>();
Map<String, Double> idList = new TreeMap<String, Double >();
//Get input File.
Scanner console = new Scanner(System.in);
System.out.println("Enter the full path to your file: ");
//Error handling in try catch for file not found
try {
String inputFileName = console.next();
//Scanner creation and varaibles
File inputFile= new File(inputFileName);
Scanner input = new Scanner(inputFile);
//Input contents number , type, price ,ID
//Loop
while (input.hasNext())
{
String Num = input.next();
String tType = input.next();
tType=tType.toUpperCase();
tSet.add(tType);
Double tPrice=Double.parseDouble(input.next());
String tAgent = input.next();
//add if record does not exist, else append to existing record
if (idList.containsKey(tAgent)) {
idList.put(tAgent, idList.get(tAgent) + tPrice);
}
else
{
idList.put(tAgent, tPrice);
}
}
input.close();
//catch for incorrect file name or no file found
} catch (FileNotFoundException exception) {
System.out.println("File not found!");
System.exit(1);
}
//Create Set iterator
Iterator iterator;
iterator = tSet.iterator();
while(iterator.hasNext()){
try {
PrintWriter report= new PrintWriter("txtx.txt");
report.println(iterator.next()+ " ");
// System.out.println(iterator.next()+ " ");
report.flush();
// report.close();
}
catch (IOException e) {
System.out.println("Error could not write to location");
}
}
}
}
【问题讨论】:
-
为什么每次迭代都创建一个新的
PrintWriter?尝试将其移到您的 while 循环之外。
标签: java iterator set printwriter