• java文件流操作


    package common;

    import java.io.*;
    import java.math.BigDecimal;
    import java.util.ArrayList;
    import java.util.List;
    import entity.Commodity;

    public class CommodityFile {
    public List<Commodity> read(){
    List<Commodity> commodities=new ArrayList<>();
    File file=new File("E:/commodities1.txt");
    FileInputStream fis=null;
    ObjectInputStream ois=null;
    //BufferedReader br=null;
    //InputStreamReader isr=null;
    try {
    file.createNewFile();
    fis=new FileInputStream(file);
    ois=new ObjectInputStream(fis);
    commodities=(List<Commodity>)ois.readObject();
    /*isr=new InputStreamReader(fis,"utf-8");
    br=new BufferedReader(isr);
    String s;
    while ((s=br.readLine())!=null){
    Commodity commoditie=new Commodity();
    String[] s1=s.split(" ");
    commoditie.setName(s1[0]);
    commoditie.setPrice(new BigDecimal(s1[1]));
    commoditie.setDetial(s1[2]);
    commodities.add(commoditie);
    }*/
    }catch (Exception e){
    e.printStackTrace();
    }
    finally {
    try {
    /*if(br!=null){
    br.close();
    }if(isr!=null){
    isr.close();
    }*/
    if(ois!=null){
    ois.close();
    }
    if(fis!=null){
    fis.close();
    }
    } catch (IOException e) {
    e.printStackTrace();
    }

    }
    return commodities;
    }
    public void write(List<Commodity>commodities){
    /*StringBuffer sb=new StringBuffer();
    for (Commodity c:commodities){
    sb.append(c.getName()+" "+c.getPrice()+" "+c.getDetial()+" ");
    }*/
    File file=new File("E:/commodities1.txt");
    FileOutputStream fos=null;
    ObjectOutputStream oos=null;
    //OutputStreamWriter osw=null;
    //BufferedWriter bw=null;
    try {
    file.createNewFile();
    fos=new FileOutputStream(file);
    oos=new ObjectOutputStream(fos);
    oos.writeObject(commodities);
    /*osw=new OutputStreamWriter(fos,"utf-8");
    bw=new BufferedWriter(osw);
    bw.write(sb.toString());*/
    } catch (Exception e) {
    e.printStackTrace();
    }finally {
    /*if(bw!=null){
    try {
    bw.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    if(osw!=null){
    try {
    osw.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }*/
    if(oos!=null){
    try {
    oos.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    if(fos!=null){
    try {
    fos.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
    }
    }
  • 相关阅读:
    14.6.1 Creating InnoDB Tables 创建InnoDB 表:
    mysql iot 主键自增列问题
    mysql iot 主键自增列问题
    perl 定义post接口
    perl 定义post接口
    [置顶] 一步步构建大型网站架构
    [置顶] 一步步构建大型网站架构
    技术人员如何面试
    技术人员如何面试
    技术人员如何面试
  • 原文地址:https://www.cnblogs.com/pursue339/p/10612840.html
Copyright © 2020-2023  润新知