【发布时间】:2018-01-31 02:03:12
【问题描述】:
我有一个按字母顺序排序的文本文件,有大约 94,000 行名称(每行一个名称,只有文本,没有标点符号。
例子:
爱丽丝
鲍勃
西蒙
西蒙
汤姆
每一行都采用相同的形式,首字母大写,没有重音字母。
我的代码:
try{
BufferedReader br = new BufferedReader(new FileReader("orderedNames.txt"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("sortedNoDuplicateNames.txt", true)));
ArrayList<String> textToTransfer = new ArrayList();
String previousLine = "";
String current = "";
//Load first line into previous line
previousLine = br.readLine();
//Add first line to the transfer list
textToTransfer.add(previousLine);
while((current = br.readLine()) != previousLine && current != null){
textToTransfer.add(current);
previousLine = current;
}
int index = 0;
for(int i=0; i<textToTransfer.size(); i++){
out.println(textToTransfer.get(i));
System.out.println(textToTransfer.get(i));
index ++;
}
System.out.println(index);
}catch(Exception e){
e.printStackTrace();
}
据我了解,正在读取文件的第一行并将其加载到 previousLine 变量中,就像我想要的那样,当前被设置为我们正在读取的文件的第二行,然后比较当前对上一行和null,如果和最后一行不一样并且不为null,我们将它添加到array-list中。
previousLine 然后设置为 currents 值,以便 current 的下一个 readLine 可以替换当前的“current”值以继续在 while 循环中进行比较。
我看不出这有什么问题。 如果找到重复项,循环肯定会中断吗?
如果发现是愚蠢的事情,请提前道歉。
【问题讨论】:
-
!(current = br.readLine()).equals(previousLine) -
List听起来不像是解决这个问题的正确数据结构。我认为您想使用Set的某些实现,因为它们不会像List那样存储重复项。最好考虑一下您对数据结构的选择,而不是随意决定ArrayList是最好的。 Check out this SO question for details
标签: java text data-manipulation