public class FilePress {
//读取文件(将数据从文件里面读出来)
public List<ProductBean> readFile(){
List<ProductBean> list = new ArrayList<ProductBean>();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("pro.txt"));
String str = "";
while((str = br.readLine()) != null){
String[] str1 = str.split("\\s+");
ProductBean bean = new ProductBean();
bean.setId(Integer.parseInt(str1[0]));
bean.setName(str1[1]);
bean.setFactory(str1[2]);
bean.setPrice(Integer.parseInt(str1[3]));
list.add(bean);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(br != null){
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return list;
}
//写入文件(将数据写入到指定的文件中)
public void writeFile(List<ProductBean> list){
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("pro.txt"));
for(ProductBean pp : list){
bw.write(pp.getId()+ " " +pp.getName()+" "+pp.getFactory()+" " +pp.getPrice()+"\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(bw != null ){
try {
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//添加数据
// public static void main(String[] args) {
//
// List<ProductBean> list = new ArrayList<ProductBean>();
//
// list.add(new ProductBean(1,"面包","成都红药食品",5));
// list.add(new ProductBean(8,"香肠","新都食品加工厂",12));
// list.add(new ProductBean(6,"腊肉","成都胖大妈",10));
// list.add(new ProductBean(5,"果粒橙","华阳高新区食品",6));
// list.add(new ProductBean(4,"汉堡","双流制造",3));
// list.add(new ProductBean(7,"可乐","德阳食品加工厂",3));
// list.add(new ProductBean(9,"纯牛奶","新疆食品加工厂",4));
// list.add(new ProductBean(11,"酸奶","双流制造",3));
//
// FilePress f = new FilePress();
// f.writeFile(list);
//
//
// }
}