zoukankan      html  css  js  c++  java
  • Java--getAbsolutePath()获取绝对路径和相对路径getPath()getName()listFiles()

    Fil类:

    getAbsolutePath()获取绝对路径

    getPath()获取相对路径

    getName()获取文件名

    list()获取指定路径下所有文件(夹)名称数组

    listFiles()获取指定目录下所有文件(夹)File数组

    import java.io.*;
    import java.nio.file.Files;
    import java.util.*;
    import java.util.regex.*;
    public class test {
        public static void main(String[] args) throws IOException{
    
    
            //在指定路径下创建文件
            File file5 = new File("C:\Users\15773\Desktop\test\file2.txt");
    //        System.out.println(file5.createNewFile());返回的是一个bool值
            boolean flag1 = file5.createNewFile();//如果文件已经存在就不创建了,返回false,如果不存在就会创建
            System.out.println("flag1 "+flag1);
    
            //创建文件夹
            File file6 = new File("C:\Users\15773\Desktop\test\test2");
            boolean flag2 = file6.mkdir();//只能创建单级目录
            System.out.println(flag2);//如果文件夹已经存在就不创建了,返回false,如果不存在就会创建
    
            //创建多级目录,mkdirs既可以穿件单级目录 也可以创建多级目录
            File file7 = new File("C:\Users\15773\Desktop\test\test3\tes6");
            boolean flag3 = file7.mkdirs();
            System.out.println(flag3);
    
            //测试是为文件或者文件夹
            System.out.println(file7.isDirectory());
            System.out.println(file7.isFile());
            System.out.println(file7.exists());
    
            String path1 = file7.getAbsolutePath();
            System.out.println("绝对路径"+path1);
            System.out.println("相对路径"+file7.getPath());
            System.out.println("只获取文件名: "+file5.getName());
    
            //获取路径下的所有文件的名称数组,返回值是数组String[]
            File file8 = new File("C:\Users\15773\Desktop\test");
            String[] names = file8.list();//返回值是String[] 不能到子目录
            for (String name : names){
                System.out.println(name);
            }
    
            System.out.println("_________________________");
            //获取指定路径下所有文件(夹)的:File 对象数组 File[]
            File[] files = file8.listFiles();
            for (File i : files){
                System.out.println(i);
                System.out.println(i.isDirectory());
            }
    
        }
    }
  • 相关阅读:
    Unable to locate package错误解决办法
    systemctl command not found
    create user, switch user
    Linux中“is not in the sudoers file”解决方法
    sed 修改文件中的行
    nvidia-cuda-toolkit install and uninstall nvidia-smi
    You can't access this shared folder because your organization's security policies block unauthenticated guest access. These policies help protect your PC
    ps auxf ps -ef ps -r cpu affinity
    message can not send, because channel is closed
    webMethods-Developer/Designer中try-catch与SQL中事务的实现
  • 原文地址:https://www.cnblogs.com/shunguo/p/14508543.html
Copyright © 2011-2022 走看看