Die Überprüfung einer Zeile befindet sich in einer Datei mit PufferedRead und HashSet
-
10-12-2019 - |
Frage
Mein Problem ist, dass ich Code schreiben muss, um zu überprüfen, ob ein Kundenname bereits in meiner TXT-Datei (customer.txt) ist.
Das Problem ist, dass ich mit Hashset überprüfe, wenn sich der Kunde in der Datei befindet, und er sagt, dass er nicht in der Datei ist, während er ist. (Es ist es manuell geprüft) Bitte helfen Sie mir, dies zu lösen.
Der Code, den ich bereits habe, ist unten. generasacodicetagpre.
dutcht code generasacodicetagpre.
Lösung
I'm really not sure what you're trying to do overall (reading every 4th line, etc.), but I wouldn't use a HashSet
if all you want is to check if a string exists in a file.
Here's a complete program for checking if a string exists in a file:
import java.io.*;
public class CheckName
{
private static boolean doesNameExistInFile(String name, String filename)
throws FileNotFoundException, IOException
{
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line = null;
try {
while ((line = reader.readLine()) != null) {
if (line.equals(name))
return true;
}
} finally {
// Always close() before exiting.
reader.close();
}
return false;
}
public static void main(String[] args)
throws FileNotFoundException, IOException
{
boolean exists = doesNameExistInFile("Bender", "input.txt");
System.out.println(exists ? "Exists!" : "Does not exist.");
}
}
Contents of input file input.txt
:
Leela
Fry
Professor
Hermes
Zoidberg
A couple of things to note:
- We don't read the entire file. We stop reading once we've found the string, as that's all we're interested in.
- Always
close()
before exiting, whether string is found or not. We put the call in thefinally
block.
Andere Tipps
This:
while ((line = br.readLine()) != null)
{
i++;
if (i == 1){hs.add(br.readLine());}
if (i % 4 == 0){hs.add(br.readLine());}
}
is probably supposed to be this:
while ((line = br.readLine()) != null)
{
i++;
if (i == 1)
hs.add(line);
if (i % 4 == 0)
hs.add(line);
}
That is — you probably meant to add
the line that you had just read, rather than reading in a new line and add
ing it.