Java 读写文件

作者: ciferlv | 来源:发表于2018-01-29 22:29 被阅读0次

    向文件中写入内容

    • 一次性把内容输入。
    public static void printToFile(String filePath, String str) throws FileNotFoundException {
            
            //new FileWriter()中的true代表不覆盖原来文件的内容,追加内容
            //清楚原来的内容则将true换为false
            PrintWriter pw = new PrintWriter(new FileWriter("./src/main/resources/rules.txt",true));
            
            //这里代表向原来文件中输入一行,与pw.println()等价
            //不换行的输入方式是pw.print()
            pw.append(str);
            
            pw.flush();
            pw.close();
        }
    
    • 想要按需要依次输入就可以在上面的代码的基础上使用pw.print()pw.println()

    从文件中读内容

    • 按行读
    Scanner in = new Scanner(new File("./src/main/resources/entity.txt"));
    while (in.hasNextLine()) {
         System.out.println(in.nextLine());
     }
    

    相关文章

      网友评论

        本文标题:Java 读写文件

        本文链接:https://www.haomeiwen.com/subject/dswfzxtx.html