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();
        }
  • 相关阅读:
    Noe4j启动警告
    SpringBoot
    MySQL数据库 java SQL语句区分大小写分析
    day24 模块的语法
    day23 re模块
    day22 常用模块02 序列化
    day21 常用模块01
    day20 面向对象06 MRO和C3算法
    day19 面向对象05 约束
    day18 面向对象04 反射
  • 原文地址:https://www.cnblogs.com/tearfc/p/5611412.html
Copyright © 2011-2022 走看看