java中如何删除本地文件夹以及文件

java中如何删除本地文件夹以及文件,第1张

删除文件夹(前提:文件夹为空以及InputStream和OutputStream等一些数据文件流关掉【close()】,否则文件无法删除)

//删除文件夹

public static void delFolder(String folderPath) {

try {

delAllFile(folderPath) //删除完里面所有内容

String filePath = folderPath

filePath = filePath.toString()

java.io.File myFilePath = new java.io.File(filePath)

myFilePath.delete() //删除空文件夹

} catch (Exception e) {

e.printStackTrace()

}

}

删除指定文件夹下的所有文件

public static boolean delAllFile(String path) {

boolean flag = false

File file = new File(path)

if (!file.exists()) {

return flag

}

if (!file.isDirectory()) {

return flag

}

String[] tempList = file.list()

File temp = null

for (int i = 0 i < tempList.length i++) {

if (path.endsWith(File.separator)) {

temp = new File(path + tempList[i])

} else {

temp = new File(path + File.separator + tempList[i])

}

if (temp.isFile()) {

temp.delete()

}

if (temp.isDirectory()) {

delAllFile(path + "/" + tempList[i])//先删除文件夹里面的文件

delFolder(path + "/" + tempList[i])//再删除空文件夹

flag = true

}

}

return flag

}

}

1、创建File对象File(String pathname):pathname录入时录入的路径字符串需要注意/和\的运用,但是由于java开发出的程序需要运用到不同的系统上,因此,一般以File.separator来代替。

2、创建File对象File(File parent,String child):此为创建文件对象的另外一种方式,parent为已创建的对象,这种情况,parent一般为文件夹的路径,child为文件的名称。

3、判断File对象是否是一个文件:isFile()返回值true为文件,false为非文件。如下程序中,由于file1对象为文件夹,非文件,返回为false;file2对象为文件,返回true。

4、文件的内容长度(占用字节):length()当前File对象所表示的文件所占用的字节量。在testFile1.txt中事先录入部分数据,file2指向的File对象,内容长度为8。

5、判断文件是否存在,在硬盘创建文件前,一般需要判断硬盘中文件是否存在,如果不存在才创建文件,这样可以避免文件重复创建。

6、文件创建:createNewFile()当File对象调用文件创建方法后,硬盘中文件才会被创建。

删除文件夹下的所有文件需要用到java.io.File类的各个方法,并需要使用简单的递归算法。

示例代码如下:

import java.io.File

public class Test

{

public static void main(String args[]){

Test t = new Test()

delFolder("c:/bb")

System.out.println("deleted")

}

//删除文件夹

//param folderPath 文件夹完整绝对路径

public static void delFolder(String folderPath) {

try {

delAllFile(folderPath)//删除完里面所有内容

String filePath = folderPath

filePath = filePath.toString()

java.io.File myFilePath = new java.io.File(filePath)

myFilePath.delete()//删除空文件夹

} catch (Exception e) {

e.printStackTrace()

}

}

//删除指定文件夹下所有文件

//param path 文件夹完整绝对路径

public static boolean delAllFile(String path) {

boolean flag = false

File file = new File(path)

if (!file.exists()) {

return flag

}

if (!file.isDirectory()) {

return flag

}

String[] tempList = file.list()

File temp = null

for (int i = 0i <tempList.lengthi++) {

if (path.endsWith(File.separator)) {

temp = new File(path + tempList[i])

} else {

temp = new File(path + File.separator + tempList[i])

}

if (temp.isFile()) {

temp.delete()

}

if (temp.isDirectory()) {

delAllFile(path + "/" + tempList[i])//先删除文件夹里面的文件

delFolder(path + "/" + tempList[i])//再删除空文件夹

flag = true

}

}

return flag

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/tougao/6044449.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-12
下一篇 2023-03-12

发表评论

登录后才能评论

评论列表(0条)

保存