zoukankan      html  css  js  c++  java
  • Java基础——文件查找创建删除

    package com.java8.filetest0823;
    
    import java.io.File;
    import java.io.IOException;
    
    public class FileTest {
        public static void main(String arg[]) {
            FileTest ft = new FileTest();
            ft.listRoots();
            ft.testCreateAndDelete("测试文件");
        }
    
        /**
         * 列出机器根目录
         */
        public void listRoots() {
            //调用File的static方法
            File[] lf = File.listRoots();
            System.out.println("磁盘上目录个数为 : " + lf.length);
            for (int i = 0; i < lf.length; i++) {
                System.out.println("第" + i + "个磁盘目录为 : " + lf[i].getAbsolutePath());
            }
        }
    
        /***
         * 测试文件的创建和删除
         * @param fileName
         */
        public void testCreateAndDelete(String fileName) {
            //通过传入名字构造File对象
            File temFile = new File(fileName);
            //判断文件是否存在
            if (temFile.exists()) {
                //若是目录
                if (temFile.isDirectory()) {
                    System.out.println("这是一个目录:" + temFile.getAbsolutePath());
                }
                //若是文件
                if (temFile.isFile()) {
                    System.out.println("这是一个文件。");
                    //打印文件长度
                    prinFileAttr(temFile);
                    //删除文件
                    temFile.delete();
                    String theName = temFile.getName();
                    String absPath = temFile.getAbsolutePath();
                    System.out.println("文件已删除,名字为:" + theName
                            + ",绝对路径为:" + absPath);
                }
            } else {
                try {
                    temFile.createNewFile();
                    System.out.println("文件已经创建!" + temFile);
                    //打印文件长度
                    prinFileAttr(temFile);
                } catch (IOException e) {
                    e.printStackTrace();//打印方法的调用情况
                    System.out.println("创建文件失败!");
                }
            }
        }
    
        /***
         * 打印文件相关属性:长度,文件名,父目录名,是否隐藏文件
         * @param temf:文件的绝对路径
         */
        public void prinFileAttr(File temf) {
            System.out.println("文件目录为:" + temf.getAbsolutePath());
            System.out.println("文件长度为:" + temf.length());
        }
    }
    
  • 相关阅读:
    扒几个 3D 模型备用
    向 3D 世界迈出一小步
    为什么说使用 Linux 系统学习 OpenGL 更方便
    Windows 下的 Linux环境
    windows git 的扩展用法——其他linux命令
    Linux 环境变量
    powershell(或者windows terminal)中使用git
    QT无边框窗体——拦截windows消息实现
    QT工具——开发技巧与其他工具
    QT工具——国际化工具
  • 原文地址:https://www.cnblogs.com/iriswang/p/11084640.html
Copyright © 2011-2022 走看看