Java 逐行读取文件内容,并解析
读取文件1.txt中的文件内容,内容格式为: 名字|性别|出生日期|政治面貌。
读取之后存在对象中。
用户类:
package main.test; import java.util.Date; public class User { private String name; private String gender; private Date birthday; private String politicsStatys; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getPoliticsStatys() { return politicsStatys; } public void setPoliticsStatys(String politicsStatys) { this.politicsStatys = politicsStatys; } @Override public String toString() { return "User [name=" + name + ", gender=" + gender + ", birthday=" + birthday + ", politicsStatys=" + politicsStatys + "]"; } }
方法类
public static List<User> getUserMsg(String path){ List<User> users = new ArrayList<User>(); File userFile = new File(path); try { FileInputStream fis = new FileInputStream(userFile); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis,"GBK")); String len = null; SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd"); while ((len = bufferedReader.readLine()) != null) { String[] strings = len.split("\\|"); User user = new User(); user.setName(strings[0]); user.setGender(strings[1]); user.setBirthday(spf.parse(strings[2])); user.setPoliticsStatys(strings[3]); users.add(user); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } return users; }