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

我需要一些帮助,将数据从文本文件读入我的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

回答:

每当我尝试运行此命令时,他们都会不断告诉我“无法解决该问题”

这意味着theword未在范围中声明。您不能访问它来调用任何方法。 他们

说对了。您需要theword在更大的范围内进行声明,或者将依赖于此的代码移到theword声明它的范围内。也许您已经在ifwhile块内声明了它,并且试图在声明它的块

使用它。那是行不通的。

每当您清理代码时,可能都会给出更详细的答案,以使代码更易读。

以上是 如何从文件中读取数据到Java中的数组? 的全部内容, 来源链接: utcz.com/qa/414078.html

回到顶部