【开发笔记】- Java写入、读取文本

文本写入

public static void createFile(String input) throws IOException {
     //设置文件路径 String filePath
= "D:/"; File dir = new File(filePath); // 一、检查放置文件的文件夹路径是否存在,不存在则创建 if (!dir.exists()) { dir.mkdirs();// mkdirs创建多级目录 } File checkFile = new File(filePath + "/SM3.txt"); FileWriter fw = null; try { // 二、检查目标文件是否存在,不存在则创建 if (!checkFile.exists()) { checkFile.createNewFile();// 创建目标文件 } // 三、向目标文件中写入内容 // FileWriter(File file, boolean append),append为true时为追加模式,false或缺省则为覆盖模式 fw = new FileWriter(checkFile, true); fw.write(input+"\r\n"); fw.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (null != fw) fw.close(); } }

文件读取

public static void readFile(String[] args)  {
        try {
            BufferedReader in = new BufferedReader(new FileReader("test.log"));
            String str;
            while ((str = in.readLine()) != null) {
                System.out.println(str);
            }
            System.out.println(str);
        } catch (IOException e) {
        }
    }

 

posted @ 2019-09-03 09:29  多搞学习少搞事情  阅读(363)  评论(0编辑  收藏  举报