写文件和读文件

本文介绍了一个简单的Java程序,该程序能够实现文件的读写功能。通过使用BufferedReader和BufferedWriter类,程序可以将一系列产品信息从文本文件中读取出来,并且能够将新的产品信息写入到同一个文件中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



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);
//  
//  
// }
 
 
 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值