day23
内容
- File类
- 递归
一.File类
1.1概述
文件和目录路径名的抽象表示 主要用于文件和目录的创建,查找和删除等操作
1.2构造方法
文件路径名
String pathname = "D:\\aaa.txt";
File file1 = new File(pathname);
文件路径名
String pathname2 = "D:\\aaa\\bbb.txt";
File file2 = new File(pathname2);
通过父路径和子路径字符串
String parent = "d:\\aaa";
String child = "bbb.txt";
File file3 = new File(parent, child);
// 通过父级File对象和子路径字符串
File parentDir = new File("d:\\aaa");
String child = "bbb.txt";
File file4 = new File(parentDir, child);
1.3 常用方法
获取功能的方法
- 返回文件的绝对路径字符串 public String getAbsolutePath()
- 将文件转化为路径名 字符串 public String getPath()
- 返回有此文件表示的文件或目录的名称 public String getName()
- 返回这个文件的长度 public long length()
绝对路径和相对路径
- 绝对路径:从盘符开始的路径,这是一个完整的路径
- 相对路径:相对于项目目录的路径,这是一个便捷的路径,开发中经常使用
判断功能的方法
- 判断文件表示的文件或目录是否实际存在 public boolean exists()
- 判断文件表示的是否为目录 public boolean isDirectory()
- 判断文件表示的是否问文件 public boolean isFile()
创建和删除功能的方法
…
1.4目录的遍历
二.递归
概述:分类
p
ublic class DiGuiDemo {
public static void main(String[] args) {
//计算1~num的和,使用递归完成
int num = 5;
// 调用求和的方法
int sum = getSum(num);
// 输出结果
System.out.println(sum);
} /
*
通过递归算法实现.
参数列表:int
返回值类型: int
*/
public static int getSum(int num) {
/*
num为1时,方法返回1,
相当于是方法的出口,num总有是1的情况
*/
if(num == 1){
return 1;
}
/*
num不为1时,方法返回 num +(num‐1)的累和
递归调用getSum方法
*/
return num + getSum(num‐1);
}
}