我正在创建一个arraylist UserArchive类并从我的User类添加User-objects:
public class UserArchive implements Serializable {
ArrayList<User> list = new ArrayList<User>();
// Inserts a new User-object
public void regCustomer(User u) {
list.add(u);
}
读取和写入此列表的最佳方法是什么?
我认为这是写它的正确方法吗?
public void writeFile() {
File fileName = new File("testList.txt");
try{
FileWriter fw = new FileWriter(fileName);
Writer output = new BufferedWriter(fw);
int sz = list.size();
for(int i = 0; i < sz; i++){
output.write(list.get(i).toString() +"\n");
}
output.close();
} catch(Exception e){
JOptionPane.showMessageDialog(null, "Kan ikke lage denne filen");
}
我曾尝试使用BufferedReader来读取文件,但无法使list.add(line)工作:
public void readFile() {
String fileName = "testList.txt";
String line;
try{
BufferedReader input = new BufferedReader(new FileReader(fileName));
if(!input.ready()){
throw new IOException();
}
while((line = input.readLine()) != null){
list.add(line);
}
input.close();
} catch(IOException e){
System.out.println(e);
}
}
我知道问题是该行是一个字符串,应该是一个用户如何。我不能使用BufferedReader来解决这个问题吗?如果是这样,我怎么想读取文件?
答案 0 :(得分:0)
最简单的方法是将每个用户转换为csv格式,前提是用户对象不复杂。
例如,您的用户类应该如下所示
public class User {
private static final String SPLIT_CHAR = ",";
private String field1;
private String field2;
private String field3;
public User(String csv) {
String[] split = csv.split(SPLIT_CHAR);
if (split.length > 0) {
field1 = split[0];
}
if (split.length > 1) {
field2 = split[1];
}
if (split.length > 2) {
field3 = split[2];
}
}
/**
* Setters and getters for fields
*
*
*/
public String toCSV() {
//check null here and pass empty strings
return field1 + SPLIT_CHAR + field2 + SPLIT_CHAR + field3;
}
}
}
在写对象时写入
output.write(list.get(i).toCSV() +"\n");
阅读时你可以打电话
list.add(new User(line));
答案 1 :(得分:0)
想象一个简单的User类,如下所示:
public class User {
private int id;
private String username;
// Constructors, etc...
public String toString() {
StringBuilder sb = new StringBuilder("#USER $");
sb.append(id);
sb.append(" $ ");
sb.append(username);
return sb.toString();
}
}
对于id = 42
和username = "Dummy"
的用户,用户字符串表示形式为:
#USER $ 42 $ Dummy
乍一看,您的代码似乎成功地将这些字符串写入文本文件(我还没有测试过)。
所以,问题在于回读信息。这样,从(在这种情况下)格式化文本中提取有意义的信息,通常称为解析。
您想从您阅读的行中解析此信息 调整代码:
BufferedReader input = null;
try {
input = new BufferedReader(new FileReader(fileName));
String line;
while((line = input.readLine()) != null) {
list.add(User.parse(line));
}
} catch(IOException e) {
e.printStackTrace();
} finally {
if (input != null) { input.close(); }
}
注意细微差别。我已将list.add(line)
替换为list.add(User.parse(line))
。这就是魔术发生的地方。让我们继续实现解析方法。
public class User {
private int id;
private String username;
// ...
public static User parse(String line) throws Exception {
// Let's split the line on those $ symbols, possibly with spaces.
String[] info = line.split("[ ]*\\$[ ]*");
// Now, we must validate the info gathered.
if (info.length != 3 || !info[0].equals("#USER")) {
// Here would go some exception defined by you.
// Alternatively, handle the error in some other way.
throw new Exception("Unknown data format.");
}
// Let's retrieve the id.
int id;
try {
id = Integer.parseInt(info[1]);
} catch (NumberFormatException ex) {
throw new Exception("Invalid id.");
}
// The username is a String, so it's ok.
// Create new User and return it.
return new User(id, info[2]);
}
}
你已经完成了!