JavaIO流_File
1.常用的文件操作
- 创建文件相关构造器方法
- new File(String pathname) //根据路径构建一个File
- new File(File parent, String child) //根据父目录文件+子路径构建一个File
- new File(String parent, String child) //根据父目录+子路径构建一个File
- 创建方法 file.createNewFile();
new file对象只是在内存(堆)中有了个对象,只有执行createNewFile方法才会真正在硬盘上创建!
+
package com.wjs.File;
import java.io.File;
import java.io.IOException;
public class TestCreateNewFile {
//方式1
public static void Create01(){
String filepath = "C:\\Users\\Laity\\Desktop\\Java全栈\\JavaIO\\Test文件\\Create01.txt";
File file = new File(filepath);
try {
file.createNewFile();
System.out.println("文件创建成功......");
} catch (IOException e) {
e.printStackTrace();
}
}
//方式2:一个父文件,一个路径
public static void Create02(){
String filepath = "C:\\Users\\Laity\\Desktop\\Java全栈\\JavaIO\\";
File parentFile = new File(filepath);
File file = new File(parentFile,"Test文件\\Create02.txt");
try {
file.createNewFile();
System.out.println("文件创建成功......");
} catch (IOException e) {
e.printStackTrace();
}
}
//方法3:一个路径,一个名字 || 两个路径
public static void Create03(){
File file = new File("C:\\Users\\Laity\\Desktop\\Java全栈\\JavaIO\\Test文件","Create03.txt");
try {
file.createNewFile();
System.out.println("文件创建成功......");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//TestCreateNewFile.Create01();
TestCreateNewFile.Create02();
//TestCreateNewFile.Create03();
}
}
- File的查找相关方法:
- getName 获取文件名字
- getAbsoutePath 获取绝对路径
- getPartent 文件父级目录
- getlength 字节长度 英文1字节 汉字3字节 int4字节
- exists 是否存在
- isFile 是不是文件
- isDirectory 是不是目录
- …
- File的增删相关方法:返回的都是boolean
- delete 删除文件或是空的文件夹,在java中目录也被当做文件
- mkdirs 创建多级目录
- mkdir 创建一级目录