File类操作文件

时间:2023-03-08 23:58:31
File类操作文件

简单示例:

     public static void main(String[] args) {
// 列出系统所有的根路径
File[] listRoots = File.listRoots();
for (File file : listRoots) {
// 相对路径
System.out.println(file.getPath()); System.out.println("空闲未使用 = " + file.getFreeSpace() / 1024 / 1024 / 1024 + "G");// 空闲空间
System.out.println("可使用 = " + file.getUsableSpace() / 1024 / 1024 / 1024 + "G");// 可用空间
System.out.println("已经使用 = " + (file.getTotalSpace() - file.getUsableSpace()) / 1024 / 1024 / 1024 + "G");// 已使用用空间
System.out.println("总容量 = " + file.getTotalSpace() / 1024 / 1024 / 1024 + "G");// 总空间
// 绝对路径
System.out.println(file.getAbsolutePath());
System.out.println();
File file2 = new File(file.getPath().charAt(0) + ":\\dick\\text1.txt");
System.out.println(file2.getPath());
System.out.println(file2.exists());
//one way
/*if (!file2.exists()) {
try {
// 创建父级目录
boolean mkdirs = file2.getParentFile().mkdirs();
System.out.println("创建" + mkdirs);
file2.createNewFile(); //new File("D://a//b//rjl.txt").createNewFile();创建失败,需要先创建目录,再创建文件
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
// other way
String path="D://a//b//c";
File directory=new File(path);
if(!directory.exists()){
boolean ms = directory.mkdirs();
System.out.println("创建:"+ms);
}else{
System.out.println("目录已存在,无需创建!");
}
String fileName="abc.txt";
File myFile = new File(path, fileName);
if(!myFile.exists()){
boolean flag;
try {
flag = myFile.createNewFile();
if(flag){
System.out.println("success!");
}else{
System.out.println("defeat!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}