您的位置 首页 > 数码极客

“java中如何创建文件夹“java如何打开文件夹…

开发项目过程中,会用到很多工具类,今天分享一个Java中File操作工具类,可以帮你节约时间,提高开发效率。

File工具类

public class CreateFileUtil {

public static boolean createFile(String destFileName) {

File file = new File(destFileName);

i()) {

Sy("创建单个文件" + destFileName + "失败,目标文件已存在!");

return false;

}

if )) {

Sy("创建单个文件" + destFileName + "失败,目标文件不能为目录!");

return false;

}

//判断目标文件所在的目录是否存在

if(!().exists()) {

//如果目标文件所在的目录不存在,则创建父目录

Sy("目标文件所在目录不存在,准备创建它!");

if(!().mkdirs()) {

Sy("创建目标文件所在目录失败!");

return false;

}

}

//创建目标文件

try {

if ()) {

Sy("创建单个文件" + destFileName + "成功!");

return true;

} else {

Sy("创建单个文件" + destFileName + "失败!");

return false;

}

} catch (IOException e) {

e.printStackTrace();

Sy("创建单个文件" + destFileName + "失败!" + e.getMessage());

return false;

}

}



public static boolean createDir(String destDirName) {

File dir = new File(destDirName);

if ()) {

Sy("创建目录" + destDirName + "失败,目标目录已经存在");

return false;

}

if (!de)) {

destDirName = destDirName + File.separator;

}

//创建目录

if ()) {

Sy("创建目录" + destDirName + "成功!");

return true;

} else {

Sy("创建目录" + destDirName + "失败!");

return false;

}

}


public static String createTempFile(String prefix, String suffix, String dirName) {

File tempFile = null;

if (dirName == null) {

try{

//在默认文件夹下创建临时文件

tempFile = File.createTempFile(prefix, suffix);

//返回临时文件的路径

return ();

} catch (IOException e) {

e.printStackTrace();

Sy("创建临时文件失败!" + e.getMessage());

return null;

}

} else {

File dir = new File(dirName);

//如果临时文件所在目录不存在,首先创建

if (!dir.exists()) {

if (!Crea(dirName)) {

Sy("创建临时文件失败,不能创建临时文件所在的目录!");

return null;

}

}

try {

//在指定目录下创建临时文件

tempFile = File.createTempFile(prefix, suffix, dir);

return ();

} catch (IOException e) {

e.printStackTrace();

Sy("创建临时文件失败!" + e.getMessage());

return null;

}

}

}

public static void main(String[] args) {

//创建目录

String dirName = "D:/work/temp/temp0/temp1";

Crea(dirName);

//创建文件

String fileName = dirName + "/temp2;;

Crea(fileName);

//创建临时文件

String prefix = "temp";

String suffix = ".txt";

for (int i = 0; i < 10; i++) {

Sy("创建了临时文件:"

+ Crea(prefix, suffix, dirName));

}

//在默认目录下创建临时文件

for (int i = 0; i < 10; i++) {

Sy("在默认目录下创建了临时文件:"

+ Crea(prefix, suffix, null));

}

}

}


以上,是我实际项目中用过的File工具类,仅供参考,有什么好的方法,可以评论区交流。

我是一名码龄10年的程序员,在这里会分享实在干货,让你少走弯路,成就精彩人生。

责任编辑: 鲁达

1.内容基于多重复合算法人工智能语言模型创作,旨在以深度学习研究为目的传播信息知识,内容观点与本网站无关,反馈举报请
2.仅供读者参考,本网站未对该内容进行证实,对其原创性、真实性、完整性、及时性不作任何保证;
3.本站属于非营利性站点无毒无广告,请读者放心使用!

“java中如何创建文件夹,java如何打开文件夹,java如何导入文件夹,java如何删除文件夹”边界阅读