实现创建一个txt文件并且读取内容,如果该文件存在则输出文件内容,如果不存在就创建文件,同时还可以写入内容
实现代码:
import java.io.*;
import java.util.Scanner;
public class test {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入文件要保存的位置");
String path = scanner.nextLine();
CreteAndRead(path);
System.out.println("请输入要写入的内容");
String str = scanner.nextLine();
Write(path,str);
}
public static void CreteAndRead(String path) throws IOException {
File file = new File(path);
if(!file.exists()){
System.out.println(file.createNewFile());
System.out.println("文件创建成功");
}else{
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
String line;
//读取读取文件内容并打印
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void Write(String path,String str) {
try(FileWriter fr = new FileWriter(path)) {
BufferedWriter bufw = new BufferedWriter(fr);
bufw.write(str);
bufw.flush();
bufw.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("未找到文件");
}
}
}
先获取输入的位置,在判断该文章存在不存在该文件,如果存在,使用while方法逐个打印内容,如果不存在,新建该文件