IO流-File-判断-重命名-获取根目录下容量

    xiaoxiao2021-03-25  100

    3. 判断

    代码如下:

     

    public class test1 { public static void main(String[] args) throws IOException { isDemo(); } public static void isDemo() throws IOException{ File f=new File("e:\\a.txt"); f.createNewFile(); //判断是否存在 boolean bf=f.exists(); System.out.println(bf); //当判断他是否为目录或者文件时,最好先判断是否存在,如果不存在都为false System.out.println(f.isFile()+"\t"+f.isDirectory()); } }

    4. 重命名

    代码如下:

     public class test2 { public static void main(String[] args) { reName(); } public static void reName(){ File f1=new File("e:\\a.txt"); File f2=new File("e:\\abc.txt"); //重名名,将a给为abc boolean b=f1.renameTo(f2); System.out.println(b); } }

    5. 系统根目录和容量获取

    代码如下:

    public class test3 { public static void main(String[] args) { listRootDemo(); } public static void listRootDemo(){ //列出系统根目录下所有的目录cdef盘符 File[] files=File.listRoots(); for(File file : files){ System.out.println(file); } //获取系统盘大小空间 File file=new File("d:\\"); System.out.println("getFreeSpace:"+file.getFreeSpace()); System.out.println("getTotalSpace:"+file.getTotalSpace()); System.out.println("getUsableSpace:"+file.getUsableSpace()); } }

     6. 获取目录内容

    代码如下:

    public class test4 { public static void main(String[] args) { fileListDemo(); } public static void fileListDemo(){ File file=new File("d:\\"); /*获取当前d盘文件夹和文件,包含隐藏的目录 *调用list方法的file对象中封装的必须是目录,否则空指针异常 *如果访问的是系统目录也会发生空指针异常 *如果目录存在但没有内容,会返回一个数组,但是长度为0 **/ String[] names=file.list(); for(String name:names){ System.out.println(name); } } }

    转载请注明原文地址: https://ju.6miu.com/read-22405.html

    最新回复(0)