目录
一、文件流
- 流:数据从数据源(文件)和程序(内存)之间的路程
- 输入流:数据从数据源(文件)到程序(内存)的路径
- 输出流:数据从程序(内存)到数据源(文件)的路径
二、 创建文件对象
一个File对象代表一个文件
/**
* 创建文件
*/
public class FileCreat {
public static void main(String[] args) {
}
//1.new File(String pathname)//根据路径构建一个File对象
@Test
public void creat01() {
String filePath = "D:\\aaaaa.txt";// 文件位置 + 文件名 \\ = /
File file = new File(filePath);//在内存中创建了一个对象 (在程序中存在,并未写入到文件中)
try {//createNewFile() 异常处理
file.createNewFile();//执行createNewFile()后才会写入到对应的位置,变成一个文件
System.out.println("创建成功");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
//2.new File(File parent,String child)//根据父目录文件+子路径构建
@Test
public void creat02() {
File parentfile = new File("D:\\");// 父目录对象位置 \\ = /
String fileName = "bbbbb.txt";// 文件名
File file = new File(parentfile, fileName);// (对象,字符串) (在程序中存在,并未写入到文件中)
try {//createNewFile() 异常处理
file.createNewFile();//执行createNewFile()后才会写入到对应的位置,变成一个文件
System.out.println("创建成功");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
//3.new File(String parent,String child) //根据父目录+子路径构建
@Test
public void creat03() {
String parentPath = "D:\\";// 文件位置 (第一个\转义符)\\ = /
String fileName = "ccccc.txt";// 文件名字
File file = new File(parentPath, fileName);// 字符串,字符串 (在程序中存在,并未写入到文件中)
try {//createNewFile() 异常处理
file.createNewFile();//执行createNewFile()后才会写入到对应的位置,变成一个文件
System.out.println("创建成功");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
三、获取文件的相关信息
/**
*一个为汉字 3个字节
*/
public class FileInformation {
public static void main(String[] args) {
//创建文件对象
File file = new File("D:\\ddddd.txt");//文件
System.out.println("文件名=" + file.getName());
System.out.println("文件绝对路径=" + file.getAbsoluteFile());
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());
}
}
四、目录操作和文件删除
/**
* 文件、目录操作和文件、目录删除
* java中目录也当作文件存在)
*/
public class Directory {
public static void main(String[] args) {
}
//1.判断文件是否存在 如果存在就删除
@Test
public void f1() {
File file = new File("D:\\ddddd.txt");//文件对象
if (file.exists()) {//判断文件是否存在
if (file.delete()) {//删除文件
System.out.println("删除成功");
}
} else {
System.out.println("文件不存在");
}
}
//2.判断目录是否存在 如果存在就删除(java中目录也当作文件存在)
@Test
public void f2() {
String filePath = "D:\\ddddd";//目录地址
File file = new File(filePath);//目录对象
if (file.exists()) {//判断目录是否存在
if (file.delete()) {//删除目录
System.out.println("删除成功");
}
} else {
System.out.println("目录不存在");
}
}
//3.判断目录(文件夹)是否存在,存在提示存在,不存在就创建
@Test
public void f3() {
String directoryPath = "D:\\ddddd";//目录路径
File file = new File(directoryPath);//目录对象
if (file.exists()) {//判断目录是否存在
if (file.delete()) {//删除目录
System.out.println(directoryPath + "目录存在");
}
} else {
System.out.println("目录不存在");
file.mkdirs();//创建目录(文件夹)
System.out.println("目录创建成功");
}
}
}