zoukankan      html  css  js  c++  java
  • Java文件File操作一:文件的创建和删除

    一、简述

      File 文件类,主要对文件进行相关操作。常用的File操作有:文件(夹)的创建、文件(夹)的删除,文件的读入和下载(复制)等;

    二、文件(夹)的创建和删除

     1、创建过程 实例:

    //create a new File
        @Test
        public void testCreateFile(){
            File m=new File("E://file");  //創建文件夾
            //判断文件夹存在否
            if(!m.exists()){
                m.mkdir(); //创建文件夹
            }
            
            File f=new File("E://file//test.txt");  //創建文件
            if(!f.exists()){
                try {
                    f.createNewFile();  //创建文件
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    2、删除过程

        //delete a file
        //@Test
        public void testDeleteFile(){
            File f=new File("E://file//test.txt"); 
            if(f.exists()){
                f.delete();
            }
        }
        
        //delete a 文件夹及下面的所有文件[采用递归之法]
        public static void testDelAllFile(String path){
            File m=new File(path); 
             File[] files=m.listFiles();  
            for(File f:files){
                if(f.isFile()){
                    f.delete();
                }else if(f.isDirectory()){
                    testDelAllFile(f.getPath());
                }
            }
            m.delete();  //最好将文件夹删除
        }
        
        public static void main(String[] args) {
            FileTest.testDelAllFile("E://file");
        }
  • 相关阅读:
    Enum, Generic and Templates
    Writing A Threadpool in Rust
    A First Look at Rust Language
    Closures in OOC
    Complexity Behind Closure
    Introduction to OOC Programming Language
    OOC,泛型,糟糕的设计。
    Enlightenment笔记
    Machine Learning/Random Projection
    Machine Learning/Introducing Logistic Function
  • 原文地址:https://www.cnblogs.com/renxiaoren/p/5280196.html
Copyright © 2011-2022 走看看