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();
        }
    }

 

posted on 2016-07-04 22:30  ..小树苗  阅读(261)  评论(0编辑  收藏  举报

导航