一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

C简单读写数据到txt文件实例

时间:2022-06-25 04:56:19 编辑:袖梨 来源:一聚教程网

 代码如下 复制代码
public void writeData2Txt(String content) {
   //存放文件的目录
    String fileDir = ServletActionContext.getServletContext().getRealPath("D:/file/");
   //简单的生成文件名
    String fileName =new  SimpleDateFormat("yyyyMMddHHmmsszzz").format(new Date())+".txt";
    File txtFile= new File(fileDir,fileName);
    BufferedReader bufferedReader = null;
    BufferedWriter bufferedWriter = null;
    try {
         bufferedReader = new BufferedReader(new StringReader(content));
         bufferedWriter = new BufferedWriter(new FileWriter(txtFile));
         char buf[] = new char[1024];         //字符缓冲区
             int len;
         while ((len = bufferedReader.read(buf)) != -1) {
             bufferedWriter.write(buf, 0, len);
         }
           
    } catch (IOException e) {
         e.printStackTrace();
    } finally {
         try {
            bufferedWriter.flush();
            bufferedWriter.close();
            bufferedReader.close();
          
         } catch (IOException e) {
            e.printStackTrace();
         }
    }
       
      
}

热门栏目