2011-12-09 4 views
1

私はちょっと検索メソッドを作ろうとしていますが、これまではint型しか検索していませんでしたが、このメソッドを実装してStringを検索することが可能かどうか疑問に思っていましたか? :私はちょうど.getTextのカップルをコーディングし、私は数だけで動作する美しい検索メカニズムを持っていますが、私は本当に文字列を検索する方法をしたい、だから私はtweeksのカップルを作ったことをやった後このコードでRandomAccessFileの文字列を検索する方法は?

//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"); 

} 
} 

**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_?で動作します。

おかげ

+2

をお勧めしますか? –

+4

は、あなたのサイトの購読を中止することがあります – DaveRlz

答えて

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)); 
} 
関連する問題