A verificação de uma linha em um arquivo com bufferedread e hashset
-
10-12-2019 - |
Pergunta
O meu problema é que eu tenho que escrever código para verificar se um nome de clientes já está no meu arquivo txt (Customers.txt).
O problema é que eu verifique com o hashset se o cliente está no arquivo e ele diz que ele não está no arquivo enquanto ele está.(Verificado manualmente) Por favor, me ajudar a resolver isso.
O código que eu já tenho é abaixo.
public class Customer {
//declaration
public static String S;
private String line ;
public String nameCustomer;
/**
* constructor
*/
public Klant(){}
/**Checking of the customer is in the file
*/
public void getCustomer() {
// make SimpleInOutDialog
SimpleInOutDialog input = new SimpleInOutDialog("Customers");
nameCustomer = input.readString("Give in the name");
try{
BufferedReader br = new BufferedReader(new FileReader("L:\\Documents/Informatica/6de jaar/GIP/Customers.txt"));
HashSet<String> hs = new HashSet<String>();
int i = 0;
while ((line = br.readLine()) != null)
{
i++;
if (i == 1){hs.add(br.readLine());}
if (i % 4 == 0){hs.add(br.readLine());}
}
if(hs.contains(nameCustomer)){
//the customer exists
input.showString("The customer exists", "");
}else{input.showString("The customer does not exist, we will make a new one", "");
setNieuweKlant();}
}catch (Exception e){//Catch when there are errors
System.err.println("Error: " + e.getMessage());}
}
/**
* make a new customer
*/
public void Make new customer(){
// make SimpleInOutDialog
SimpleInOutDialog input = new SimpleInOutDialog("A new customer");
//input
S = "Name customer: " + input.readString("Give in your name:");
WriteToFile();
S = "Adress: " + input.readString("Give your adress");
WriteToFile();
S = "Telephonenummber: " + input.readString("Give your telephonenumber");
WriteToFile();
//making a customerID
UUID idCustomer = UUID.randomUUID();
S = "CustomerID: " + customerID.toString();
WriteToFile();
}
/**
* Schrijft de gegevens weg naar het bestand
*/
public void WriteToFile(){
try{
FileWriter writer = new FileWriter("L:\\Documents/Informatica/6de jaar/GIP/Customer.txt", true);
BufferedWriter out = new BufferedWriter(writer);
//Wrting away your data
out.write(S);
//Closing the writer
out.close();
}catch (Exception e){//Catch when there are errors
System.err.println("Error: " + e.getMessage());
}
}
Dutcht Código
public class Klant {
//declaratie van de variabele die de tekst voorsteld
public static String S;
private String line ;
public String naamklant;
/**
* constructor
*/
public Klant(){}
/**Controleerd of de klant al bestaat
*/
public void getKlant() {
// SimpleInOutDialog aanmaken
SimpleInOutDialog input = new SimpleInOutDialog("Klanten");
naamklant = input.readString("Geef de volledige naam in");
try{
BufferedReader br = new BufferedReader(new FileReader("L:\\Documents/Informatica/6de jaar/GIP/Klanten.txt"));
HashSet<String> hs = new HashSet<String>();
int i = 0;
while ((line = br.readLine()) != null)
{
i++;
if (i == 1){hs.add(br.readLine());}
if (i % 4 == 0){hs.add(br.readLine());}
}
if(hs.contains(naamklant)){
//klant bestaat
input.showString("De klant bestaat", "");
}else{input.showString("De klant bestaat niet, er wordt een nieuwe klant aangemaakt", "");
setNieuweKlant();}
}catch (Exception e){//Catch wanneer er errors zijn
System.err.println("Error: " + e.getMessage());}
}
/**
* Maakt een nieuwe klant aan
*/
public void setNieuweKlant(){
// SimpleInOutDialog aanmaken
SimpleInOutDialog input = new SimpleInOutDialog("Een nieuwe klant");
//input
S = input.readString("Geef de volledige naam in");
WriteToFile();
S = "Adres: " + input.readString("Geef het adres op");
WriteToFile();
S = "Telefoonummer: " + input.readString("Geef het telefoonnummer op");
WriteToFile();
//een klantennummer aanmaken
UUID idKlant = UUID.randomUUID();
S = "Klantnummer: " + idKlant.toString();
WriteToFile();
}
/**
* Schrijft de gegevens weg naar het bestand
*/
public void WriteToFile(){
try{
FileWriter writer = new FileWriter("L:\\Documents/Informatica/6de jaar/GIP/Klanten.txt", true);
BufferedWriter out = new BufferedWriter(writer);
//uw gegevens wegschrijven
out.write(S);
out.newLine();
//de writer sluiten
out.close();
}catch (Exception e){//Catch wanneer er errors zijn
System.err.println("Error: " + e.getMessage());}
}
}
Solução
Eu realmente não estou certo de que você está tentando fazer total (leitura de cada linha 4, etc.), mas eu não iria usar um HashSet
se tudo o que você deseja é verificar se existe uma seqüência de caracteres em um arquivo.
Aqui está um completo programa para verificar se existe uma seqüência de caracteres em um arquivo:
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.");
}
}
Conteúdo do arquivo de entrada input.txt
:
Leela
Fry
Professor
Hermes
Zoidberg
Um par de coisas a observar:
- Nós não ler o arquivo inteiro.Nós parar de ler depois que descobrimos a cadeia, já que é tudo em que estamos interessados.
- Sempre
close()
antes de sair, se a cadeia for encontrado ou não.Vamos colocar a chamada emfinally
bloco.
Outras dicas
Este:
while ((line = br.readLine()) != null)
{
i++;
if (i == 1){hs.add(br.readLine());}
if (i % 4 == 0){hs.add(br.readLine());}
}
é, provavelmente, deveria ser este:
while ((line = br.readLine()) != null)
{
i++;
if (i == 1)
hs.add(line);
if (i % 4 == 0)
hs.add(line);
}
Que é — você provavelmente queria add
a linha que você acabou de ler, em vez de ler em um novo linha e add
ing-lo.