我正在编写一个程序,该程序应该创建一个文件,然后生成一个唯一的id,读取该文件,如果它中存在任何重复项,则生成一个新的id并重复检查。
截至目前,我可以创建id并写入文件。但我的问题是我'我无法检查文件中是否存在任何重复项。
以下是我尝试的代码:
public class Main {
public static void main(String a[]) throws IOException {
File file = new File("text.txt");
file.createNewFile();
FileWriter filewriter = new FileWriter(file.getAbsoluteFile(), true);
filewriter.write("\r\n");
BufferedWriter bw = new BufferedWriter(filewriter);
String alphanumeric = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Random random = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++) {
// randomInteger = random.nextInt();
sb.append(alphanumeric.charAt(random.nextInt(alphanumeric.length())));
}
System.out.println("\n Random Alphanumeric in Java: " + sb.toString());
// reading data from file
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String string;
while((string = br.readLine()) != null) {
if(string.equals(sb.toString())) {
for (int i = 0; i < 10; i++) {
// randomInteger = random.nextInt();
sb.append(alphanumeric.charAt(random.nextInt(alphanumeric.length())));
}
bw.write((sb.toString()));
System.out.println("new value :" + sb.toString());
}
else{
System.out.println("existing value :" +sb.toString());
}
}
System.out.println(sb.toString());
} catch (FileNotFoundException fnfe) {
System.out.println("File not found!!");
}
}
}
答案 0 :(得分:0)
这里有几个问题 1:
if(string.equals(sb.toString())) {
for (int i = 0; i < 10; i++) {
// randomInteger = random.nextInt();
sb.append(alphanumeric.charAt(random.nextInt(alphanumeric.length())));
}
bw.write((sb.toString()));
System.out.println("new value :" + sb.toString());
}
这会增加现有ID,因为sb
永远不会重置为空。
2: 你现在在做的是:
generate id
for each line L do
if L equals id
append to ID
write id
else
some output
end for
你应该做什么:
while not inserted
generate id
for each line L do
if L equals id
found = true
break // exit for each
end for
if found
continue //restart while loop
insert into file // we only get here if it was not found
inserted = true
end while
为了获得更好的性能,首先将所有ID读入列表,然后使用它来检查现有ID,而不是每次都读取文件。