文件读取
文件读取需要用 File 对象构造一个 Scanner 对象。
Scanner scan = new Scanner(Paths.get("test.txt"), "GBK");
写入文件
构造一个 PrintWriter。
PrintWriter writer = new PrintWriter("test.text", "GBK");
可以像 System.out 那样使用 print、printf、println 等向文件写入内容。
一定记得关闭 IO 流
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Paths;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
String dir = System.getProperty("user.dir");//获取当前工作路径
/* 构造一个 PrintWriter */
PrintWriter writer = new PrintWriter("test.txt", "GBK");
/*写入内容*/
writer.println("甲:Are you ok?");
writer.println("乙:I'm fine,thanks.");
writer.close();//必须关闭io流
/*Scanner 读取文件*/
Scanner scanner = new Scanner(Paths.get(dir+"\\test.txt"), "GBK");
System.out.println(scanner.nextLine());
System.out.println(scanner.nextLine());
}
}
实现效果:
甲:Are you ok?
乙:I'm fine,thanks.