我希望我的程序一次读取一行输入,并将每一行写入输出,如果它不是之前输入行的副本。而且,具有大量重复行的文件使用的内存不会超过唯一行数所需的内存。
重复行的打印次数应与它们在输入中出现的次数相同我已经完成了一半的问题,但仍然无法正常工作..
public class Part1 {
public static void doIt(BufferedReader r, PrintWriter w) throws IOException {
Set<String> s = new HashSet<String>();
String inpt;
int n = 0;
while ((inpt = r.readLine()) != null) {
s.add(inpt);
n++;
}
Iterator<String> i = s.iterator();
while (i.hasNext()) {
w.println(i.next());
}
}
public static void main(String[] args) {
try {
BufferedReader r;
PrintWriter w;
if (args.length == 0) {
r = new BufferedReader(new InputStreamReader(System.in));
w = new PrintWriter(System.out);
} else if (args.length == 1) {
r = new BufferedReader(new FileReader(args[0]));
w = new PrintWriter(System.out);
} else {
r = new BufferedReader(new FileReader(args[0]));
w = new PrintWriter(new FileWriter(args[1]));
}
long start = System.nanoTime();
doIt(r, w);
w.flush();
long stop = System.nanoTime();
System.out.println("Execution time: " + 10e-9 * (stop-start));
} catch (IOException e) {
System.err.println(e);
System.exit(-1);
}
}
}
}