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

     读取:

    public static void ss()  throws Exception{
            String filePath = "C:\Users\acer\Desktop\111.txt";
            StringBuilder sb = new StringBuilder();  
            String re = "";
            String encoding="gbk";
            File file=new File(filePath);
            if(file.isFile() && file.exists()){ //判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                new FileInputStream(file),encoding);//考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                int i = 0;
                while((lineTxt = bufferedReader.readLine()) != null){
                    lineTxt = lineTxt.trim();
                    sb.append(lineTxt);
                    i++;
                }
                re = sb.toString();
                System.out.println(re.length());
                read.close();
            }
        }

     追加内容:

    public static synchronized void appendLog(String newLog,String filePath) {
            Scanner sc = null;
            PrintWriter pw = null;
            File log = new File(filePath);
            try {
                if(!log.exists()){//如果文件不存在,则新建.
                    File parentDir = new File(log.getParent());
                    if(!parentDir.exists()){//如果所在目录不存在,则新建.
                        parentDir.mkdirs();
                    }
                    log.createNewFile();
                }
                pw = new PrintWriter(new FileWriter(log), true);
                pw.println(newLog);//写入新日志.
                pw.close();
            }catch(IOException ex){
                ex.printStackTrace();
            }
        }
  • 相关阅读:
    Python 执行主程序
    Python 3.0 写日志时出现乱码
    验证文件下载成功
    selenium 校验文件下载成功
    java中Proxy(代理与动态代理)
    简易计算器
    Python正则
    Python logger 没打出行数
    Python logger /logging
    Python configparser 读取指定节点内容失败
  • 原文地址:https://www.cnblogs.com/lishupeng/p/5641920.html
Copyright © 2011-2022 走看看