how to read data from file into array? java

Posted by lox on Stack Overflow See other posts from Stack Overflow or by lox
Published on 2010-05-05T22:03:22Z Indexed on 2010/05/05 22:08 UTC
Read the original article Hit count: 226

Filed under:
|

I need some help reading data from a txt file into my ArrayList. I know the code is pretty messy, but just try to take a look at it. The first part with the creating and putting the ArrayList into the txt file works perfectly. I just need some help at the end in the "marked" area.

Sorry if I still have some words in my native language, but I didn't really had the time to translate everything.

public class ContAngajat {

 String username;
 String password;



}




public class CreazaCont {

// creating the arraylist and putting it into a file 

public static void  ang(String args[])   { 

    ArrayList<ContAngajat> angajati=new ArrayList<ContAngajat>(50);

 Scanner diskScanner = new Scanner(in);

 Scanner forn = new Scanner(in);


 int n;

     out.print("Introduceti numarul de conturi noi care doriti sa le introduceti: ");
     n=forn.nextInt();
  out.println();

     try{

    FileWriter fw = new FileWriter("ConturiAngajati.txt", true);


    for(int i=0; i<n; i++){
  ContAngajat cont = new ContAngajat();

  out.print("Username: ");
  cont.username=diskScanner.nextLine();


  out.print("Password: ");
  cont.password=diskScanner.nextLine();

  angajati.add(cont);

  fw.write(cont.username + " ");
  fw.write(cont.password +"|");


  }
  fw.close();
     }
     catch(IOException ex){

      System.out.println("Could not write to file");

      System.exit(0);
     }




 for (int i=0; i<n; i++) {
  out.println("username: " + angajati.get(i).username + "  password: " +angajati.get(i).password );

 }


  }


// HERE I'M TRING TO GET THE ARRAYLIST OUT OF THE FILE

public static void  RdAng(String args[])   { 

 ArrayList<ContAngajat> angajati=new ArrayList<ContAngajat>(50);
 ContAngajat cont = new ContAngajat();
 int count,i2,i;

 try{


   FileReader fr = new FileReader("ConturiAngajati.txt");
   BufferedReader br = new BufferedReader(fr);

   String line = "";


   while((line=br.readLine())!=null) {

   String[] theline=line.split("|"); 
   count=theline.length;

   for(i=0;i<theline.length;i++) {

   String[] theword = theline[i].split(" "); 
  }     

   }   

   for(i2=0;i2<count;i2++)  {

   ContAngajat contrd = new ContAngajat();

// "ERROR" OVER HERE 

 for (int ird=0; ird <theword.length; ird++) {  

 cont.username=theword[0];
     cont.password=theword[1];

// they keep telling me "theword cannot be resolved" whenever i try to run this

}
       angajati.add(contrd); 
 }

 } 


 catch(IOException ex){

      System.out.println("Could not read to file");

      System.exit(0);
     }
}


}

© Stack Overflow or respective owner

Related posts about java

Related posts about arraylist