描述:创建两个文件对象,分别使用相对路径和绝对路径创建。
答案
操作步骤:
绝对路径创建文件对象:使用File类一个参数的构造方法。
相对路径创建文件对象:使用File类两个参数的构造方法。
代码:
public class Test01_01 {
public static void main(String[] args) {
// 创建文件对象:绝对路径
File f1 = new File("d:/aaa/a.txt");
// 创建文件对象:相对路径
File f2 = new File("a.txt");
}
}
描述:检查D盘下是否存在文件a.txt,如果不存在则创建该文件。
答案
操作步骤:
代码:
public class Test01_02 {
public static void main(String[] args) throws IOException{
// 创建文件对象:绝对路径
File f = new File("d:/a.txt");
// 如果文件不存在,则创建文件
if(!f.exists()) {
f.createNewFile();
}
}
}
描述:在D盘下创建一个名为bbb的文件夹。
答案
操作步骤:
代码:
public class Test01_03 {
public static void main(String[] args) {
// 创建文件对象
File f = new File("d:/bbb");
// 创建单级文件夹
f.mkdir();
}
}
描述:在D盘下创建一个名为ccc的文件夹,要求如下:
1.ccc文件夹中要求包含bbb子文件夹
2.bbb子文件夹要求包含aaa文件夹
答案:
操作步骤:
代码:
public class Test01_04 {
public static void main(String[] args) {
// 创建文件对象
File f = new File("d:/ccc/bbb/aaa");
// 创建多级文件夹
f.mkdirs();
}
}
描述:
将D盘下a.txt文件删除
将D盘下aaa文件夹删除,要求文件夹aaa是一个空文件夹。
答案:
操作步骤:
代码:
public class Test01_05 {
public static void main(String[] args) {
// 创建文件对象
File f = new File("d:/a.txt");
// 删除文件
f.delete();
// 创建文件夹对象
File dir = new File("d:/aaa");
// 删除文件夹
dir.delete();
}
}
描述:
获取D盘aaa文件夹中b.txt文件的文件名,文件大小,文件的绝对路径和父路径等信息,并将信息输出在控制台。
答案:
操作步骤:
代码:
public class Test01_06 {
public static void main(String[] args) {
// 创建文件对象
File f = new File("d:/aaa/b.txt");
// 获得文件名
String filename = f.getName();
// 获得文件大小
longfilesize = f.length();
// 获得文件的绝对路径
String path = f.getAbsolutePath();
// 获得父文件夹路径,返回字符串
String parentPath = f.getParent();
// 获得父文件夹路径,返回文件对象
File parentFile = f.getParentFile();
// 输出信息
System.out.println("文件名:" + filename);
System.out.println("文件大小:" + filesize);
System.out.println("文件路径:" + path);
System.out.println("文件父路径:" + parentPath);
System.out.println("文件父路径:" + parentFile);
}
}
描述:
1.判断File对象是否是文件,是文件则输出:xxx是一个文件,否则输出:xxx不是一个文件。
2.判断File对象是否是文件夹,是文件夹则输出:xxx是一个文件夹,否则输出:xxx不是一个文件夹。(xxx是文件名或文件夹名)
答案:
操作步骤:
代码:
public class Test01_07 {
public static void main(String[] args) {
// 创建文件对象
File f1 = new File("d:/b.txt");
// 判断是否是一个文件
if(f1.isFile()) {
System.out.println(f1.getName()+"是一个文件");
} else {
System.out.println(f1.getName()+"不是一个文件");
}
// 创建文件对象
File f2 = new File("d:/aaaa");
// 判断是否是一个文件夹
if(f2.isDirectory()) {
System.out.println(f2.getName()+"是一个文件夹");
} else {
System.out.println(f2.getName()+"不是一个文件夹");
}
}
}
描述:
获取指定文件夹下所有的文件,并将所有文件的名字输出到控制台。
注意:不包含子文件夹下的文件
答案
操作步骤:
代码:
public class Test01_08 {
public static void main(String[] args) {
// 创建文件对象
File f = new File("d:/aaa");
// 获得文件夹下所有文件
File[] files = f.listFiles();
// 遍历文件数组
for (File file :files) {
// 将文件的名字打印到控制台
System.out.println(file.getName());
}
}
原文:https://www.cnblogs.com/Polar-sunshine/p/13475055.html