package com.day14io;
import java.io.File;
public class Test {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
// File(String pathname):将一个字符串路径封装成File对象
// File(String parent,String child):传入一个父级路径和子级路径
// File(File parent,String child):传入一个File类型的父级路径和子级路径
// File file=new File("d:///hhhh.txt");
// File file2=new File("a.txt");
//
// System.out.println(file2.createNewFile());
//
// File file3=new File("b");
//
// System.out.println(file2.getName());
try {
File file = new File("E:/newfile.txt");
// 创建一个新文件
boolean fvar = file.createNewFile();
// public long length()返回由此抽象路径名表示的文件的长度。如果此路径名表示一个目录,则返回值是不确定的。
Long long12 = file.length();
System.out.println(long12);
// 判断是否已存在该文件
if (fvar) {
System.out.println("File has been created successfully!");
} else {
System.out.println("File already present at the specified location!");
}
// 打印出文件名、文件路径以及父目录
System.out.println(file.getName() + "\t" + file.getPath() + "\t" + file.getParent());
// 删除文件
file.delete();
System.out.println(file.getName());
} catch (Exception e) {
// TODO: handle exception
System.out.println("Exception Occurred:");
e.printStackTrace();
}
// 得到绝对路径file3.getAbsolutePath()
File file3 = new File("obj");
file3.createNewFile();
System.out.println(file3.getName());
System.out.println(file3.getAbsolutePath());
// 判断该文件是否是一个文件夹
boolean haha = file3.isDirectory();
if (!haha) {
System.out.println("该文件是一个文件夹");
}
// 返回此抽象路径名表示的文件最后一次被修改的时间。
Long long1 = file3.lastModified();
System.out.println(long1);
// 删除此抽象路径名表示的文件或目录。
file3.delete();
// 在虚拟机终止时,请求删除此抽象路径名表示的文件或目录。
file3.deleteOnExit();
// 判断文件是否存在
boolean hh = file3.exists();
if (!hh) {
System.out.println("文件已经被删除");
}
System.out.println(file3.getName());
// 文件夹操作
File file = new File("E:\\wocnima");
// 创建文件夹
boolean flag = file.mkdir();
// 打印出文件名、文件路径以及父目录
System.out.println(file.getName() + "\t" + file.getParent() + "\t" + file.getPath());
File file2 = new File("E:\\wocnima\\hhhhh\\aaaa\\bbbb\\vvvv\\jjjj");
// 创建多级文件夹
System.out.println(file2.mkdirs());
// 打印出文件名、文件路径以及父目录
System.out.println(file2.getName() + "\t" + file2.getParent() + "\t" + file2.getPath());
}
}
File类随意练习
最新推荐文章于 2022-02-16 20:37:57 发布