binary search from a file - java

how can I search a data using binary search? When if statement begins, the program goes to IOException block. It seems that it doesn't try to read the file.
public void busquedaDicotomica1(String clave)
{
String lectura1=null, lectura2=null ;
long posicion;
long tamaño;
long midValue;
boolean valido = true;
try
{
rafObj = new RandomAccessFile("indice1.ind","r");
tamaño = rafObj.length();
midValue = tamaño/2;
rafObj.seek(midValue);
if(clave.equalsIgnoreCase(rafObj.readUTF()))
{
System.out.println("ok");
}
else
{
System.out.println("no");
}
}
catch(EOFException eoe)
{}
catch(FileNotFoundException nfe)
{
VentanaPrincipal.setErrorText(dialogo);
}
catch(IOException ioe)
{
VentanaPrincipal.setErrorText(ioe.getMessage());
}
}
}

Related

Why can't I add text to a file in Java? [duplicate]

This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 3 years ago.
It seems that its creating a new file always I try to write or read.
Each line starts with the name of the player, if exists the player should add the score at the end, if not creates a new line and write the info.
.......................
public class JogadorData {
private String nome_player;
private Scanner is;
private FileWriter os;
// this file exists
private final String path = "src/Data/JogadorData";
public JogadorData(String nome_player) {
this.nome_player = nome_player;
try {
is = new Scanner(new File(path));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
os = new FileWriter(path);
} catch (IOException e) {
e.printStackTrace();
}
}
public void escreverScore(String score) {
if (jogadorNovo(nome_player)) {
try {
os.write(nome_player + " " + score);
} catch (IOException e) {
e.printStackTrace();
}
}
else {
escreverResultadoJogadorExistente(score);
}
try {
is.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// returns true if it is a new player
private boolean jogadorNovo(String nome_player) {
while (is.hasNextLine()) {
String linha = is.nextLine();
String[] info = linha.split(" ");
if (info[0].equals(nome_player)) {
return false;
}
}
return true;
}
}
....................................
....................................
Test:
public class TESTE {
public static void main(String[] args) {
JogadorData jogador = new JogadorData("Manelina");
jogador.escreverScore("100");
// System.out.println(jogador.lerMelhorResultado());
}
}
The example below is a simplified read/write to file from what you have, done in similar format to what you are trying to do. What this code does is reads every line from the file you are loading from via Files#readAllLines, then runs through each line, (put your logic where I commented the if statement, and then output.add appends the new version of the line you are modifying, storing it in the array list "output", after which the file is saved to the path defined by Files#write
List<String> output = new ArrayList<>();
List<String> lines = Files.readAllLines(Paths.get("Path/To/File.txt"));
for (String line : lines) {
//... if (playerExists(line))
output.add(line + " " + score);
}
Files.write(Paths.get("Path/To/Save/File.txt"), output);

Reading numbers from a .txt file in java and adding them

I have a text file with some account holders and numbers of books they have on loan. I need to read the file, add how many account there are and add the total number of books.
These are the account holders and the total number of books.
Tim Newton 14
Leon Jones 21
Bill Bob 94
Sarah Gooding 67
{
private int count;
private File inFile, outFile;
private Scanner input;
private String name;
private PrintWriter output;
private int total;
public test(String name, String id, String inFileName, String outFileName) {
inFile = new File(inFileName);
if (!inFile.exists()) {
throw new IllegalStateException(inFileName + " does not exist");
}
outFile = new File(outFileName);
}
public void makeLink() throws FileNotFoundException {
input = new Scanner(inFile);
output = new PrintWriter(outFile);
}
public void processFiles() {
try {
while (input.hasNext()) {
String line = input.nextLine();
output.println(line);
}
} catch (NullPointerException e) {
System.out.println(" Scanner not assigned");
}
}
public void closeLink() {
try {
input.close();
} catch (NullPointerException e) {
System.out.println(" Scanner not assigned");
}
try {
output.close();
} catch (NullPointerException e) {
System.out.println(" PrintWriter not assigned");
}
}
}
Here is the edited code with the scanner answer implemented:
public void makeLink() throws FileNotFoundException {
input = new Scanner(inFile);
output = new PrintWriter(outFile);
numbers = new Scanner(inFile)
}
public void processFiles() {
try {
// your current code then
while (account.hasNextInt()) {
String line = input.nextLine()
while (numbers.hasNextInt()) {
total += numbers.nextInt();
}
output.println(line);
}
} catch (NullPointerException e) {
System.out.println(" Scanner not assigned");
}
}
enter code here
Use scanner.hasNextInt() and scanner.nextInt()
You may want to have another scanner that looks for numbers in the file:
private Scanner account; // initialise this in makeLink
public void processFiles() {
try {
// your current code then
while (account.hasNextInt()) {
total += account.nextInt();
}
} catch (NullPointerException e) {
System.out.println(" Scanner not assigned");
}
}
Note: It is worthwhile to read the java API.

Catching ArrayIndexOutOfBoundsExc

public static void main(String[]args){
Scanner in = new Scanner(System.in);
int col=6;
int row=7;
String[][] tablero=new String[col][row];
rellenarTablero(tablero);
int grid = row*col;
for(int count=0;count<=grid;count++){
if(count%2==0){
jugador1(tablero,in);
}
else{
jugador2(tablero,in);
}
}
}
public static void jugador1(String[][] tablero,Scanner in){
int row=7;
int col1=preguntarHastaAcertar(in,"Jugador1!Que columna?");
for(row=row-1;row>=0;row--){
if(tablero[col1][row]=="."){
tablero[col1][row]="X";
break;
}
}
imprimirTablero(tablero);
}
public static void jugador2(String[][] tablero,Scanner in){
int row=7;
int col2=preguntarHastaAcertar(in,"Jugador2!Que columna?");
for(row=row-1;row>=0;row--){
if(tablero[col2][row]=="."){
tablero[col2][row]="O";
break;
}
}
imprimirTablero(tablero);
}
public static void rellenarTablero (String[][] tablero){
int col;
int row;
for(row=0;row<7;row++){
for(col=0;col<6;col++){
tablero[col][row]=".";
}
}
}
public static void imprimirTablero (String[][] tablero){
int col;
int row;
for(row=0;row<7;row++){
for(col=0;col<6;col++){
System.out.print(tablero[col][row]);
}
System.out.println(" ");
}
}
public static int preguntarHastaAcertar (Scanner in,String mensaje){
while(true){
System.out.print( mensaje );
String linea =in.nextLine();
try{
return (Integer.parseInt(linea)-1);
}
catch (NumberFormatException e){
System.out.print(linea+" no es un numero!");
}
catch(ArrayIndexOutOfBoundsException ex){
System.out.println(linea+" no es un columna correcta!");
}
}
}
How do I put a catch for ArrayIndexOutOfBoundsException e in this along with the numberFormatExcp e ?I want it too show a mesege that the column selected is not correct and keep asking me until getting the column that will actualy work.Im kinda learnind :D
An ArrayIndexOutOfBoundsException should generally not be handled as it is considered as a programming error. However, if you want to do this.. just write it the more natural way :
try {
for(row=row-1;row>=0;row--) {
if(tablero[col1][row]==".") {
tablero[col1][row]="X";
break;
}
}
} catch (ArrayIndexOutOfBoundsException ex) {
// do something
}
However, from your edited message, it would be better to do something like this :
public static int preguntarHastaAcertar (Scanner in, String mensaje, int nrows){
System.out.print(mensaje);
String linea = in.nextLine();
try {
int value = Integer.parseInt(linea) - 1;
if (value >= 0 && value < nrows)
return value;
else {
System.out.print(linea + " no es una columna correcta!");
return preguntarHastaAcertar(in,mensaje,nrows);
}
} catch (NumberFormatException e){
System.out.print(linea + " no es un numero!");
return preguntarHastaAcertar(in,mensaje,nrows);
}
}
Just tag on another catch statement..
try{
return (Integer.parseInt(linea)-1);
}
catch (NumberFormatException e){
System.out.print(linea+" is not a number!");
} catch(ArrayIndexOutOfBoundsException error){}

Problems with RMS to store persistent data

1.Problem on emulator:
I am launching my midlet app at first time is to store some data and then I am restarting it at second time is to read the stored data. It is working well in first two cases without any exception.
However I am restarting it second time on the same way then It gives exception: "Uncaught exception java/lang/NumberFormatException:" it is processing only char and total data is less than 64 kb.
2.Problem on real device:
RMS is not working at all. I don't know if I need to give a permission for the handset (nokia n95).
Thanks.
In app, it is only storing charity companies into rms according to a selected country. So if a country is already selected, it must skip country list and then display company list in every restart.
In below code, rms_Check() method is to check the data in order to open country or company list frame.
public class X {
private static RecordStore rs =null;
private static Vector rms_Vector = new Vector();
static final String REC_STORE ="db_1";
public X() {
}
public void openRecStore(){
try {
rs = RecordStore.openRecordStore(REC_STORE, true);
System.out.println("open record store");
} catch (Exception e)
{
db(e.toString()+" in openRecStore");
}
}
public void closeRecStore(){
try {
rs.closeRecordStore();
} catch (Exception e) {
db(e.toString()+" in closeRecStore");
}
}
public void deleteRecStore()
{
if (RecordStore.listRecordStores()!=null){
try {
RecordStore.deleteRecordStore(REC_STORE);
} catch (Exception e) {
db(e.toString()+" in deleteRecStore");
}
}
}
public void writeRecord(String str) throws UnsupportedEncodingException
{
byte[] rec = str.getBytes("UTF-8");
try {
rs.addRecord(rec, 0, rec.length);
System.out.println("write record store");
} catch (Exception e) {
db(e.toString()+" in writeRecord");
}
}
public void readRecord()
{
try {
// Intentionally it is too small to test code
byte[] m_enc = new byte[5];
byte[] recData = new String(m_enc).getBytes("UTF-8");
int len;
for(int i =1; i<= rs.getNumRecords(); i++){
if(rs.getRecordSize(i)> recData.length)
recData = new byte[rs.getRecordSize(i)];
len = rs.getRecord(i, recData, 0);
System.out.println("Record #"+i+":"+new String(recData, 0, len));
System.out.println("------------------------");
rms_Vector.addElement(new String(recData, 0, len));
}
} catch (Exception e) {
db(e.toString() +" in readStore");
}
}
private void db(String str)
{
System.out.println("Msg:"+str);
}
public Vector rms_Array(){
return this.rms_Vector;
}
public boolean rms_Check(){
if(this.rms_Vector.size()>0){
System.out.print("rms_check: true");
// if true it will display company list every time
return true;
}else{
System.out.print("rms_check: false");
//if false it will display country list then company list
return false;
}
}
}
Use this
private RecordStore rs = null; // Record store
public String REC_STORE = "RSM name"; // Name of record store
public int record_max=0;
public void openRecStore(){
try{
rs = RecordStore.openRecordStore(REC_STORE, true );
}catch (Exception e){}
}
public void closeRecStore(){
try{
rs.closeRecordStore();
}catch (Exception e){}
}
public void deleteRecStore(){
if (RecordStore.listRecordStores() != null){
try{
RecordStore.deleteRecordStore(REC_STORE);
}catch (Exception e){}
}
}
public void writeRecord(String str){
byte[] rec = str.getBytes();
try{
rs.addRecord(rec, 0, rec.length);
}catch (Exception e){}
}
public void readRecords(){
try{
byte[] recData = new byte[5];
int len;
record_max=rs.getNumRecords();
for(int i = 1; i <= record_max; i++){
if(rs.getRecordSize(i) > recData.length){
recData = new byte[rs.getRecordSize(i)];
}
len = rs.getRecord(i, recData, 0);
file_name[i]=new String(recData, 0, len);
}
}catch (Exception e){}
}
you have file_name[] array of save data
for load actin commad use :
openRecStore();
readRecords();
for(int j=1;j<=record_max;j++ ) {
System.out.println("Record " + j + " : " + file_name[j]);
}
closeRecStore();
and save this :
openRecStore();
writeRecord(textField.getString());
closeRecStore();

Reading an Object from a file to an ArrayList

When Im trying to read an object and store in arraylist but im getting an exception this is the part of code where im facing a problem.
public class Customer implements Serializable {
private String username;
private String password;
private int age;
private String accttype;
private String acctno;
private float amount;
Customer() {
System.out.println("Im in Customer");
}
public boolean writeToDataBase(String uname, String pwd, int cage, String caccttype, String cacctno, float camount) throws IOException {
Customer custobj = new Customer();
FileOutputStream fos=null;
ObjectOutputStream oos=null;
custobj.username = uname;
custobj.password = pwd;
custobj.age = cage;
custobj.accttype = caccttype;
custobj.acctno = cacctno;
custobj.amount = camount;
try {
fos=new FileOutputStream("Customerdetails.txt",true);
oos=new ObjectOutputStream(fos);
oos.writeObject(custobj);
oos.close();
fos.close();
return true;
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
finally
{
fos.close();
oos.close();
}
}
public boolean retriveFromDataBase(int a) throws IOException
{
try {
Customer custobj = new Customer();
FileInputStream fis=null;
ObjectInputStream ois=null;
ArrayList<Customer> custlist;
try {
custlist = new ArrayList<Customer>();
fis = new FileInputStream("Customerdetails.txt");
ois = new ObjectInputStream(fis);
while (fis.available()!=0) {
custobj=(Customer)ois.readObject();
custlist.add(custobj);
}
System.out.println("Customer List" + custlist.size());
if (a == 3) {
for (int i = 0; i < custlist.size(); i++) {
custobj = custlist.get(i);
custobj.displayCustomers();
}
}
return true;
} catch (Exception ex) {
System.out.println(ex.toString());
System.out.println("No users are presnt in the file");
return false;
}
finally
{
ois.close();
fis.close();
}
}
catch(Exception ex)
{
System.out.println(ex.toString());
return false;
}
}
public void displayCustomers()
{
try
{
System.out.println("details"+username+"\t"+age+"\t"+password+"\t"+acctno+"\t"+accttype+"\t"+amount);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
Does your object implement the Serializiable or Externalizeable interface? If yes do you use non transitive objects that don't implement serializiable/externalizeable and don't offer a argumentless default constructor?
Without further information (which exception, more code) it's hard to say.
I noted that the program throws java.io.StreamCorruptedException, when you run it for the second time. It works fine when you run it only once.
The problem is that you cannot APPEND to the same file : Customerdetails.txt every time you serialize in writeToDatabase(..) method. So remove the append flag : "true" in the call to constructor of FileOutputStream in writeToDatabase(..) method.

Categories