zoukankan      html  css  js  c++  java
  • java 写入与读取txt文件

    写入:

        File writefile;  
        String path = request.getSession().getServletContext().getRealPath("/") + "log";
        String content = "123";
        try
        {
            writefile = new File(path);
            if (writefile.exists() == false)  // 如果文本文件不存在则创建它
            {
            writefile.mkdir();
            writefile = new File(path);  // 重新实例化
            }
            FileWriter filewriter = new FileWriter(writefile + "//log.txt");// 写入新的文件内容
            filewriter.write(content);
            filewriter.close();
            filewriter.flush();
        }
        catch (Exception d)
        {
            System.out.println(d.getMessage());
        }
    request.getSession().getServletContext().getRealPath("/")为获取程序路径

    读取:
        try
        {
            String encoding = "GBK";
            File file = new File(request.getSession().getServletContext().getRealPath("/") + "log" + "//log.txt");
            if (file.isFile() && file.exists())
            { // 判断文件是否存在
            InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 考虑到编码格式
            BufferedReader bufferedReader = new BufferedReader(read);
            String lineTxt = null;
            while ((lineTxt = bufferedReader.readLine()) != null)
            {
                System.out.println(lineTxt);
            }
            read.close();
            }
            else
            {
            System.out.println("找不到指定的文件");
            }
        }
        catch (Exception e)
        {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
  • 相关阅读:
    jqueryui 进度条使用
    第一阶段站立会议03
    第一阶段站立会议02
    第一阶段站立会议01
    找到了——电梯会议
    软件需求规格说明书
    团队项目计划会议
    软件开发团队简介
    找水王
    NABCD需求分析
  • 原文地址:https://www.cnblogs.com/tearfc/p/5611412.html
Copyright © 2011-2022 走看看