文件的增加、删除、查询

文件的增加、删除、查询,第1张

文件的增加、删除、查询 创建文件
 public static void main(String[] args) {
        //创建一个普通的文件
        File file = new File("D:0.txt");//路径
        try {
            boolean flag = file.createNewFile();//创建一个文件,文件存在不创建,不存在则创建
            System.out.println(flag?"success":"fail");//返回一个标记,判断创建是否成功
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
创建单个文件夹
try {
    File file1 = new File("D:\WorkPlace\something0");
    boolean flag =file1.mkdir();//mkdir创建单个文件夹,存在不创建
    System.out.println(flag?"success_1":"fail_1");
} catch (Exception e) {
    e.printStackTrace();
}
创建多个文件夹
try {
            File file2 = new File("D:\WorkPlace\something014");
            boolean flag2 = file2.mkdirs();//mkdirs创建多个文件夹,存在不创建
            System.out.println(flag2?"success_2":"fail_2");
        } catch (Exception e) {
            e.printStackTrace();
        }
文件的删除
public static void main(String[] args) {
        File file = new File("D:\WorkPlace\something0");
        boolean flag = file.delete();//delete删除由此抽象路径名表示的文件或目录。
        System.out.println(flag?"success":"fail");
    }
文件的查询 判断文件是否存在
 File file = new File("D:\WorkPlace\something");
        boolean flag = file.exists();//判断文件是否存在
        if(flag){
            System.out.println("文件已经存在");
        }else {
            file.mkdir();
            System.out.println("文件创建成功");
        }
查询文件的大小
//2.获取文件的大小
        File file1 = new File("D:\WorkPlace\something0.txt");
        try {
            file1.createNewFile();
            long size = file1.length();
            System.out.println("size: "+size);
        } catch (IOException e) {
            e.printStackTrace();
        }


//String字符串: length(),返回字符串中字符的个数
//数组: 数组名.length ,是属性,获取数组中元素的个数
//集合: 集合对象名.size(),返回集合中元素的个数
查询文件名
String name = file1.getName();
System.out.println("文件名:"+name);
查询路径
//4.获取文件的路径
            String path = file1.getPath();
            System.out.println("文件路径:"+path);
            String path1 = file1.getAbsolutePath();
            System.out.println(path1);


递归查询所有路径
package com.io;

import java.io.File;

public class FileDemo04 {
    public static void showFile(String pathname){
        File f1 = new File(pathname);
        boolean flag1 = f1.isDirectory();//判断文件是否是文件夹
        if(flag1){//是文件夹
            File[] files = f1.listFiles();
            for(int i=0;files!=null && i					
										


					

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5712843.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存