java 读取与写入文件(字符流)

作者: adm 分类: java 发布时间: 2021-08-16

java 读取与写入文件

public static void writeFile(){
    String strPath = "H:\\bbb\\aa\\tt.txt";

    try {
        File file = new File(strPath);
        File fileParent = file.getParentFile();
        if(!fileParent.exists()){
            fileParent.mkdirs();
        }
        //此判断可以不要 
        if(!file.exists()){
            file.createNewFile();
        }
        BufferedWriter out=new BufferedWriter(new FileWriter(file));
        out.write("wo shi");
        out.newLine();
        out.write("yin");
        out.newLine();
        out.write("ye ye");
        out.close();
    } catch (IOException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
}

public static void readFile(){
    String strPath = "H:\\bbb\\aa\\tt.txt";
    BufferedReader in = null;
    try {
         in=new BufferedReader(new FileReader(strPath));
        String line = null;
        try {
            while ((line = in.readLine()) !=null){
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }finally {
        //关闭BufferedReader
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!