如何读取.txt文件中的多行?
//WRITE A ELEMENT OF ARRAY TO TXT
public static void write_array_element(Persona value,String path) throws IOException{
BufferedWriter out = new BufferedWriter(new FileWriter(new File(path),true));
out.write(value.name);
out.newLine();
out.write(value.surname);
out.newLine();
out.write(value.d);
out.newLine();
out.write(value.m);
out.newLine();
out.write(value.y);
out.newLine();
out.newLine();
out.flush();
out.close();
}
此函数在追加写入模式下以.txt格式写入五行,在其他函数中,我读取用于设置元素的五行,但不读取所有行,而仅读取前五行,而忽略其他行。
//READ ELEMENT OF ARRAY FROM TXT
public static Persona read_from_txt(String path) throws IOException, ClassNotFoundException{
BufferedReader in = new BufferedReader(new FileReader(new File(path)));
String name = in.readLine();
String surname = in.readLine();
String d = in.readLine();
String m = in.readLine();
String y = in.readLine();
Persona tmp = new Persona(name,surname,d,m,y);
return tmp;
}
使用in.readLine();我可以读取这五个元素的行,但是当我尝试设置从txt到数组的所有元素时,我只会得到txt的第一个元素。 帮我 ?
答案 0 :(得分:0)
我需要设定EOF周期,但是如何?
while((line = in.readLine()) != null){
//...
}
此外,在Persona类中创建一个方法,该方法将返回可用于txt的personas值。这样您就可以立即编写角色信息。 例如:
String printPersona(){ return name + "\n" + surname + "\n" + ... }
(或您可以将其命名为toString())