如何在Java中从文件读取数据到数组?

时间:2010-05-05 22:03:23

标签: java file-io arraylist

我需要一些帮助才能将文本文件中的数据读入我的ArrayList。创建ArrayList并将其放入文本文件的第一部分非常有效。我只是在“标记”区域的最后需要一些帮助。

请注意,有些标识符是我的母语。

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);
     }
}


}

编译错误为theword cannot be resolved

1 个答案:

答案 0 :(得分:2)

  每当我试图运行这个

时,他们就会一直告诉我“这个词无法解决”

这意味着范围中未声明theword。您无法访问它以调用任何方法。 他们是对的。您需要在更广泛的范围内声明theword,或者将依赖于theword的代码移动到声明它的范围内。也许你已经在ifwhile块左右声明了它,并且你试图在外面使用声明它的块。那不行。

每当您清理代码时,都可以给出更详细的答案,以便更好地阅读。