使用IO流创建文件,三种方式
package IO流.CreateFile;
import java.io.File;
import java.io.IOException;
/**
* @program:多线程和IO
* @descripton:创建新文件
* @author:ZhengCheng
* @create:2021/10/4-13:24
**/
public class CreateNewFile {
public static void main(String[] args) {
CreateNewFile cnf = new CreateNewFile();
cnf.createNewFile01("e:\\new1.txt");
cnf.createNewFile02("e:\\","new2.txt");
cnf.createNewFile03("e:\\","new3.txt");
}
//路径与文件名
public void createNewFile01(String filepath){
File file = new File(filepath);
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
//父路径+子名
public void createNewFile02(String father,String child){
File file = new File(father,child);
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
//父文件加子名字
public void createNewFile03(String father,String child){
File Ffile = new File(father);
File file = new File(Ffile,child);
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
一些基本的File的API
public void fileInfo(){
File file = new File("e:\\new1.txt");
System.out.println("文件名字=" + file.getName());
System.out.println("文件绝对路径=" + file.getAbsolutePath());
System.out.println("文件父级目录=" + file.getParent());
System.out.println("文件大小(字节)=" + file.length());
System.out.println("文件是否存在=" + file.exists());
System.out.println("是不是一个文件=" + file.isFile());
System.out.println("是不是一个目录=" + file.isDirectory());
}
删除文件,一般的文件,和空文件夹,我们都可以直接使用delete删除。但是如果文件夹中存在东西,那么,我们需要使用别的方法。
基础删除方法:
File file = new File("e:\\new1.txt");
if (file.exists()){
file.delete();
}
删除内含文件的文件夹(包括该文件夹)
public void dirsDelete(String path) {
File file = new File(path);
String[] fileContent = file.list();
for (String conPath : fileContent) {
File file1 = new File(file, conPath);
//递归向下删除
if (file1.isDirectory()) {
dirsDelete(file1.getAbsolutePath());
file1.delete();//空了,删除
} else {
file1.delete();
}
}
file.delete();//删除最顶层父目录,没有这句话可以当做清空path文件夹。
}
本文介绍了使用Java IO流的三种方法创建文件,并展示了如何获取文件信息以及删除文件和包含文件的文件夹。内容包括:创建新文件、获取文件属性(如名称、路径、大小等)、基础文件删除以及递归删除含文件的文件夹。通过实例代码详细解析了每个操作的实现过程。

1061

被折叠的 条评论
为什么被折叠?



