当前位置: 移动技术网 > IT编程>开发语言>Java > Java创建文件夹及文件实例代码

Java创建文件夹及文件实例代码

2019年07月22日  | 移动技术网IT编程  | 我要评论

复制代码 代码如下:

package com.xhkj.util;

import java.io.file;
import java.io.ioexception;

public class createfileutil {

public static boolean createfile(string destfilename) {
    file file = new file(destfilename);
    if (file.exists()) {
     system.out.println("创建单个文件" + destfilename + "失败,目标文件已存在!");
     return false;
    }
    if (destfilename.endswith(file.separator)) {
     system.out.println("创建单个文件" + destfilename + "失败,目标不能是目录!");
     return false;
    }
    if (!file.getparentfile().exists()) {
     system.out.println("目标文件所在路径不存在,准备创建。。。");
     if (!file.getparentfile().mkdirs()) {
      system.out.println("创建目录文件所在的目录失败!");
      return false;
     }
    }

    // 创建目标文件
    try {
     if (file.createnewfile()) {
      system.out.println("创建单个文件" + destfilename + "成功!");
      return true;
     } else {
      system.out.println("创建单个文件" + destfilename + "失败!");
      return false;
     }
    } catch (ioexception e) {
     e.printstacktrace();
     system.out.println("创建单个文件" + destfilename + "失败!");
     return false;
    }
}

public static boolean createdir(string destdirname) {
    file dir = new file(destdirname);
    if(dir.exists()) {
     system.out.println("创建目录" + destdirname + "失败,目标目录已存在!");
     return false;
    }
    if(!destdirname.endswith(file.separator))
     destdirname = destdirname + file.separator;
    // 创建单个目录
    if(dir.mkdirs()) {
     system.out.println("创建目录" + destdirname + "成功!");
     return true;
    } else {
     system.out.println("创建目录" + destdirname + "成功!");
     return false;
    }
}

public static string createtempfile(string prefix, string suffix, string dirname) {
    file tempfile = null;
    try{
    if(dirname == null) {
     // 在默认文件夹下创建临时文件
     tempfile = file.createtempfile(prefix, suffix);
     return tempfile.getcanonicalpath();
    }
    else {
     file dir = new file(dirname);
     // 如果临时文件所在目录不存在,首先创建
     if(!dir.exists()) {
      if(!createfileutil.createdir(dirname)){
       system.out.println("创建临时文件失败,不能创建临时文件所在目录!");
       return null;
      }
     }
     tempfile = file.createtempfile(prefix, suffix, dir);
     return tempfile.getcanonicalpath();
    }
    } catch(ioexception e) {
     e.printstacktrace();
     system.out.println("创建临时文件失败" + e.getmessage());
     return null;
    }
}

public static void main(string[] args) {
    // 创建目录
    string dirname = "c:/test/test0/test1";
    createfileutil.createdir(dirname);
    // 创建文件
    string filename = dirname + "/test2/testfile.txt";
    createfileutil.createfile(filename);
    // 创建临时文件
    string prefix = "temp";
    string suffix = ".txt";
    for(int i = 0; i < 10; i++) {
     system.out.println("创建了临时文件:" + createfileutil.createtempfile(prefix, suffix, dirname));
    }

}

}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网