文件的创建
- 方式1: new File(String pathName) 根据路径构建一个File对象
- 方式2: new File(File parent,String child) 根据父目录文件+子路径构建
- 方式3: new File(String parent,String child) 根据父目录+子路径构建
代码:
//方式1 new File(String pathName) 根据路径构建一个File对象
public void creat1() {
String pathName = "d:\\creatFile\\file1.txt";
File file1 = new File(pathName);
try {
file1.createNewFile();
System.out.println("文件1创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
//方式2 new File(File parent,String child) 根据父目录文件+子路径构建
public void creat2(){
File parent = new File("d:\\");
String child = "file2.txt";
File file2 = new File(parent, child);
try {
file2.createNewFile();
System.out.println("文件2创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
//方式3 new File(String parent,String child) 根据父目录+子路径构建
public void creat3(){
String parent = "d:\\";
String child = "file3.txt";
File file2 = new File(parent, child);
try {
file2.createNewFile();
System.out.println("文件3创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
常用方法
- getName():获取文件名字。
- getAbsolutePath():获取文件的绝对路径。
- getParent():获取文件的父级目录。
- length():获取文件的大小(以字节为单位)。
- exists():判断文件是否存在。
- isFile():判断是否为一个文件。
- isDirectory():判断是否为一个目录。
- delete():删除文件
- mkdirs():创建多级目录
- mkdir():创建父目录(一级目录)
代码:
public void fileMethods(){
//先创建文件对象
File file = new File("d:\\file1.txt");
//调用相应的方法,得到对应信息
System.out.println("文件名字=" + file.getName());
//getName、getAbsolutePath、getParent、length、exists、isFile、isDirectory
System.out.println("文件绝对路径=" + file.getAbsolutePath());
System.out.println("文件父级目录=" + file.getParent());
System.out.println("文件大小(字节)=" + file.length());
System.out.println("文件是否存在=" + file.exists());//T
System.out.println("是不是一个文件=" + file.isFile());//T
System.out.println("是不是一个目录=" + file.isDirectory());//F
}
public void delete(){
File file1 = new File("d:\\file3.txt");
if(!file1.exists()){
System.out.println("文件不存在");
}else {
if(file1.delete()){
System.out.println("文件删除成功");
}else {
System.out.println("文件删除失败");
}
}
}
public void delete2(){
File file1 = new File("d:\\file1");
if(!file1.exists()){
System.out.println("文件不存在");
}else {
if(file1.delete()){
System.out.println("文件删除成功");
}else {
System.out.println("文件删除失败");
}
}
}
public void creat(){
String directoryPath = "d:\\file1\\ret";
File file = new File(directoryPath);
if(file.exists()){
System.out.println("文件存在");
}else {
if(file.mkdirs()){//mkdirs()创建多级目录,如:d:\\file1\\ret。mkdir()创建父一级目录,如d:\\file2
System.out.println("文件创建成功");
}else {
System.out.println("文件创建失败");
}
}
}