向文件中写入内容
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());
}