java写入内容到本地文件 -读取文件内容

/** 日志记录
     * @author sys
     * @param content 要写入的类容
     * @param path 目标路径 c:/log/
     * @param filename 文件名 log.txt
     */
    public static void writeFileToLoaction(String content,String path,String filename) {
        try {
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
            File f = new File(path+"//"+filename);
            if(!f.exists())
                f.createNewFile();
            
            FileWriter fw = new FileWriter(f.getAbsoluteFile(),true);//追加
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content+"\r\n\r\n\r\n");
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 读文件 text
     */
    public static String getStringstrByLocation(String filepath) {
        StringBuilder bufferstr=new StringBuilder();
        InputStreamReader contentfile = null ;
        BufferedReader Inputfile = null ;
        try {
            File f = new File(filepath);
            if (!f.exists()) {
                f.createNewFile();
            }
             contentfile = new InputStreamReader(
                    new FileInputStream(f), "UTF-8");
             Inputfile = new BufferedReader(contentfile);
            String filerecord = "";
            while ((filerecord=Inputfile.readLine()) != null) {
                bufferstr.append(filerecord);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }finally{
            try {
                Inputfile.close();
                contentfile.close();
            } catch (IOException e) {
                //e.printStackTrace();
            }
        }
        return bufferstr.toString();
    }

    public static void main(String[] args) {
        System.out.println(getStringstrByLocation("c:/log/123.txt"));
    }

 


 

posted @ 2017-10-27 11:16  冬天不眠  阅读(827)  评论(0编辑  收藏  举报