Java知识总结

Java 读写文件

2018-01-29  本文已影响0人  ciferlv

向文件中写入内容

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

从文件中读内容

Scanner in = new Scanner(new File("./src/main/resources/entity.txt"));
while (in.hasNextLine()) {
     System.out.println(in.nextLine());
 }
上一篇 下一篇

猜你喜欢

热点阅读