Java基础 IO流的文件和目录的五类主要操作

时间:2022-05-11 03:45:56

笔记:

/**  IO流的 文件和目录的操作
* 1.路径需要 需要两个反斜杠 或者一个单斜杠!
* 绝对路径:包括盘符在内的完整的路径名!
* 相对路径:在当前目录文件下的路径!
* 2.File 是一个类,有构造器,对应一个文件或者文件目录!
* 3.File类对象与平台无关.
* 4.访问文件名:
* getName()
* getPath()
* getAbsoluteFile()
* getAbsolutePath()
* getParent()
* renameTo(File newName) ,移动文件或文件夹到newName的地方
* 5.文件检测
* exists()
* canWrite()
* canRead()
* isFile()
* isDirectory()
* 6.获取常规文件信息
* lastModified() ,最后修改时间
* length() ,返回由此抽象路径名表示的文件的长度
* 7.文件操作相关
* createNewFile() //创建的文件是调用这个方法的 对象里的内容
* delete()
* 8.目录操作相关
* mkDir() ,创建由此抽象路径名命名的目录 (要求目录齐全!)
* mkDirs() ,//创建由此抽象路径名命名的目录,包括任何必需但不存在的父目录。
* 请注意,如果此操作失败,它可能已成功创建一些必需的父目录。
* list() //返回一个字符串数组,命名由此抽象路径名表示的目录中满足指定过滤器的文件和目录
* listFiles() //返回一个抽象路径名数组,列出所有的文件及目录
*
*
*/

测试代码:

public class IO流 {
@Test
public void test1(){
File file1=new File("D:\\SZS文件夹\\IO\\hello.txt");
File file2=new File("D:\\SZS文件夹\\IO3\\1.txt"); //不存在的目录
System.out.println(file1.getName());
System.out.println(file1.getPath());
System.out.println("************");
System.out.println(file1.exists());
System.out.println(file1.canWrite());
System.out.println(file1.canRead());
System.out.println(file1.isFile());
System.out.println("file1文件的字符长度: "+file1.length());
System.out.println(new Date(file1.lastModified()));
System.out.println("************");
System.out.println(file1+"进行删除: "+file1.delete());
if(!file1.exists()) { //执行一次createNewFile()操作!
boolean b=true;
try {
if (file1.createNewFile()) b = true;
else b = false;
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(file1+"的createNewFile: "+b);
} System.out.println(file2.mkdirs()); //创建目录文件
File file3=new File("D:\\SZS文件夹");
String[] names= file3.list(); //返回file3 的目录名的 字符串数组
for(int i=0;i<names.length;i++)
System.out.print("\t"+names[i]);
System.out.println(); }
}

测试结果:

hello.txt
D:\SZS文件夹\IO\hello.txt
************
true
true
true
true
file1文件的字符长度: 0
Tue Oct 16 15:25:29 CST 2018
************
D:\SZS文件夹\IO\hello.txt进行删除: true
D:\SZS文件夹\IO\hello.txt的createNewFile: true
false
IO IO3