1

我正在尝试做一个小的搜索方法,到目前为止我有一个只搜索 int 类型的方法,我一直想知道是否有可能重新实现这个方法来搜索字符串?

//Searches only ints
public void buscarCliente_Codigo(int cod) throws IOException{ /*cod is for the input
for eg. a textfield input which im using*/

try{
RandomAccessFile f = new RandomAccessFile("Clientes.txt","rw"); //.txt File name
boolean encontrado=false;
registroExistente = false ;
long bytes = 0;
do{
codigo = f.readInt();
nombre = leerNombre(f);    //Reads String
numTelefono = leerNumTelefono(f);
direccion = leerDireccion(f);
seguro = leerSeguro(f);
nacionalidad = leerNacionalidad(f);
cedula = leerCedula(f);
if(cod==codigo){
iCodigoBusqueda = codigo;
encontrado=true;
registroExistente = true;
break;
}else{
iCodigoBusqueda = 0;  //Type int
registroExistente = false;
}
bytes +=1;//Changes
f.seek(bytes);
}
while(bytes<f.length());
f.close();
}  catch (Exception e){
registroExistente = false;
JOptionPane.showMessageDialog(null,"Data not found");

}
}

之后,我只编写了几个 .getText 代码,并且我有一个漂亮的搜索机制,它只适用于数字,但我真的想要一个搜索字符串的方法,所以我做了几个 tweeks:

**enter code here**
public void buscarCliente_Nombre(String nom) throws IOException{ //change to String

try{
RandomAccessFile f = new RandomAccessFile("Clientes.txt","rw");
boolean encontrado=false;
registroExistente = false ;
long bytes = 0;
do{
codigo = f.readInt();
nombre = leerNombre(f);
numTelefono = leerNumTelefono(f);
direccion = leerDireccion(f);
seguro = leerSeguro(f);
nacionalidad = leerNacionalidad(f);
cedula = leerCedula(f);
if(nom.equals(nombre)){
iNombreString = nombre;
encontrado=true;
registroExistente = true;
break;
}else{
iNombreString = ""; //String type
registroExistente = false;
}
bytes +=1;//cambios
f.seek(bytes);
}
while(bytes<f.length());
f.close();
}  catch (Exception e){
registroExistente = false;
JOptionPane.showMessageDialog(null,"Data not found");

}

}

它不起作用,它给了我例外。

那么无论如何这段代码是否适用于Strings_?

谢谢

4

1 回答 1

0

您可以在字符串中找到子字符串吗?是的。

老实说,我不知道您在那里尝试做什么,或者我知道“RandomAccessFile”是什么,但如果它只是一个普通文件,为什么不像一个一样阅读它。

//Read the file... I don't bother to show how...
string = //the data of the file...
if(string.contains("Substring")) {
System.out.println("Substring could be found");
}
else {
System.out.println("Substring could not be found");
}

如果您正在尝试阅读 xml 之类的内容,我建议您

if(string.contains("Substring=\"")) {
int pos = string.indexOf("Substring=\"")+"Substring=\"".length();
return string.substring(pos,string.indexOf("\"",pos));
}
于 2011-12-29T17:24:36.817 回答