我正在尝试制作一个小搜索方法,到目前为止我有一个仅搜索 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 代码,并且有了一个仅适用于数字的漂亮搜索机制,但我真的想要一个搜索字符串的方法,所以我花了几个星期:
**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_?
谢谢
最佳答案
你能在字符串中找到子字符串吗?是的。
老实说,我不知道你想在那里做什么,或者我知道“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));
}
关于java - 如何使用此代码在 RandomAccessFile 中搜索字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8440459/