数据写入到TXT文档中

public class FileWrite {
    public File file;
    public FileOutputStream stream = null;
  
    //每次写入都会覆盖之前的内容
    public void writeData(String name,String data){
        try{
            String path = "E:/data/" + name +".txt";
            file = new File(path);
            stream = new FileOutputStream(file);
            if(!file.exists()){
                file.createNewFile();
            }
            byte[] contentInbytes = data.getBytes();
            stream.write(contentInbytes);
            stream.flush();
            stream.close();


        }catch (FileNotFoundException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

   //在末尾追加内容,不会覆盖之前的内容
    public void write(String name,String data){
        try{ String path = "E:/data/" + name +".txt";
            file = new File(path);
            FileWriter fw = new FileWriter(file,true);
            PrintWriter pw = new PrintWriter(fw);
            pw.print(data);
            pw.flush();
            pw.close();
            fw.close();
        }catch (IOException e){
            e.printStackTrace();
        }

    }
    }

  

posted @ 2018-07-19 16:05  爱吃橙子  阅读(358)  评论(0编辑  收藏  举报