我在我的UserArchive类中创建了一个数组列表,并从我的User类中添加了用户对象:
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(行)正常工作:
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做这件事吗?如果是这样,我应该如何读取该文件?
发布于 2013-05-01 03:03:52
最简单的方法是将每个用户转换为csv格式,前提是用户对象不复杂。
例如,您的user类应该如下所示
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));
发布于 2013-05-01 03:08:15
想象一个简单的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(User.parse(line))替换了list.add(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]);
}
}你就完事了!
https://stackoverflow.com/questions/16306771
复制相似问题