File类实现文件、文件夹的创建、写入、查看、修改、删除
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.FileNotFoundException;
public class TestFile {
public static void main(String[] args) throws IOException {
//创建文件夹
File folder = new File("D:/Test");
try {
if(!folder.exists()){
folder.getParentFile().mkdirs(); //若文件夹不存在,则创建
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("创建文件夹:" + folder.mkdirs());
System.out.println("文件路径:" + folder.getAbsoluteFile());
//创建文件
File file = new File("D:/Test/TestFile.txt"); //文件本身
// File file = new File("/TestFile.txt"); //盘符+当前路径
// File file = new File("TestFile.txt"); //上下文路径+当前路径
try {
if(!file.exists()){
file.getParentFile().mkdirs(); //若文件不存在,则创建
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("创建文件" + file.createNewFile());
System.out.println("文件路径:" + file.getAbsoluteFile());
//写入文件
try {
FileWriter fw = new FileWriter("D:/Test/TestFile.txt");
BufferedWriter bw = new BufferedWriter(fw);
bw.write("hi,java"); //写数据
bw.flush(); //刷新流
bw.close(); //关闭资源
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
//查看文件
BufferedReader br = null;
try {
FileReader fr = new FileReader(file);
br = new BufferedReader(fr);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String str = br.readLine();
br.close();
System.out.println(str);
//修改文件
BufferedReader br1;
try {
BufferedWriter bw1 = new BufferedWriter(new FileWriter("D:/Test/TestFile.txt"));
bw1.write("hi,php"); //写数据
bw1.flush(); //刷新流
bw1.close(); //关闭资源
} catch (IOException e) {
e.printStackTrace();
}
br1 = new BufferedReader(new FileReader(file));
String str1 = br1.readLine();
br1.close();
System.out.println(str1);
//删除文件
try {
if(file.exists()){
System.out.println("删除文件:" + file.delete());
}
} catch (Exception e) {
e.printStackTrace();
}
//删除文件夹
try {
if(folder.exists()){
System.out.println("删除文件夹:" + folder.delete());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}