我有这段代码,我已经看过很多次了。它似乎过滤了很多,但有些重复可以通过?
import java.io.*;
import java.util.*;
class ipstoblockfilter {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("E:\alp\ipstoblock.txt");
try {
Scanner sc = new Scanner(file);
try
{
PrintWriter printWriter = new PrintWriter("E:\alp\ipstoblockfiltered.txt");
while (sc.hasNextLine()) {
String nextLine = sc.nextLine();
Scanner nextLineParser = new Scanner(nextLine);
// check if duplicate
File filefiltered = new File("E:\alp\ipstoblockfiltered.txt");
try {
Scanner scff = new Scanner(filefiltered);
List<String> arrayList = new ArrayList<String>();
while (scff.hasNextLine()) {
arrayList.add(scff.nextLine());
} //While
if (!arrayList.contains(nextLine)) {
printWriter.println(nextLine);
}
} //duptry
catch (FileNotFoundException e) {
e.printStackTrace();
} //dupcatch
// check if duplicate
} //while
printWriter.close();
}
catch (FileNotFoundException ex)
{
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
} //Main
} // Class
这怎么可能?
如果有什么需要我研究或改变的地方,请告诉我!
谢谢你的帮助!
编辑:
所以我尝试了andrewdleach的代码,并产生了以下错误
[错误]
ipstoblockfilter.java:7: error: incompatible types: File cannot be converted to Reader
BufferedReader reader = new BufferedReader(file);
^
ipstoblockfilter.java:15: error: cannot find symbol
Printwriter writer = new PrintWriter(file);
^
symbol: class Printwriter
location: class ipstoblockcommands
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
2 errors
[/error]
这是我试过的他的密码[代码]
import java.io.*;
import java.util.*;
class ipstoblockcommands {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("E:\alp\ipstoblock.txt");
BufferedReader reader = new BufferedReader(file);
Set<String> lineSet= new HashSet<>();
while (reader.readLine() != null) {
lineSet.add(reader.readLine().trim());
}
reader.close();
Printwriter writer = new PrintWriter(file);
Iterator<String> iterator = lineSet.iterator();
while (iterator.hasNext()) {
writer.write(iterator.next());
}
writer.close();
} //Main
} // Class
[/code]
从代码中,您一次分析一行,如果Arraylist不包含您的行,则使用PrintWriter进行编写。好的
但是,您正在尝试同时从同一文件读取和打印。
相反,将每一行读取到Strings的数据结构中,删除重复项,然后在对所有适当的数据进行排序和解析后写回文件。
编辑:
import java.io.*;
import java.util.*;
public class IpScanner {
public IpScanner() {
}
private void start() {
try {
File file = new File("FILE_PATH\ipstoblock.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
Set<String> lineSet= new HashSet<>();
while (reader.readLine() != null) {
lineSet.add(reader.readLine().trim());
}
reader.close();
PrintWriter writer = new PrintWriter(file);
Iterator<String> iterator = lineSet.iterator();
while (iterator.hasNext()) {
writer.write(iterator.next() + "rn");
}
writer.close();
} catch (IOException e) {
System.err.println("Couldn't parse");
}
}
public static void main(String[] args){
new IpScanner().start();
}
}