java删除文件目录
A. java文件删除
java删除文件或文件夹的具体步骤:
1、验证传入路径是否为正确的路径名(Windows系统,其他系统未使用)
// 验证字符串是否为正确路径名的正则表达式
private static String matches = "[A-Za-z]:\\\\[^:?\"><*]*";
// 通过 sPath.matches(matches) 方法的返回值判断是否正确
// sPath 为路径字符串
2、通用的文件夹或文件删除方法,直接调用此方法,即可实现删除文件夹或文件,包括文件夹下的所有文件
/**
* 根据路径删除指定的目录或文件,无论存在与否
*@param sPath 要删除的目录或文件
*@return 删除成功返回 true,否则返回 false。
*/
public boolean DeleteFolder(String sPath) {
flag = false;
file = new File(sPath);
// 判断目录或文件是否存在
if (!file.exists()) { // 不存在返回 false
return flag;
} else {
// 判断是否为文件
if (file.isFile()) { // 为文件时调用删除文件方法
return deleteFile(sPath);
} else { // 为目录时调用删除目录方法
return deleteDirectory(sPath);
}
}
}
3、实现删除文件的方法
/**
* 删除单个文件
* @param sPath 被删除文件的文件名
* @return 单个文件删除成功返回true,否则返回false
*/
public boolean deleteFile(String sPath) {
flag = false;
file = new File(sPath);
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists()) {
file.delete();
flag = true;
}
return flag;
}
4、实现删除文件夹的方法
/**
* 删除目录(文件夹)以及目录下的文件
* @param sPath 被删除目录的文件路径
* @return 目录删除成功返回true,否则返回false
*/
public boolean deleteDirectory(String sPath) {
//如果sPath不以文件分隔符结尾,自动添加文件分隔符
if (!sPath.endsWith(File.separator)) {
sPath = sPath + File.separator;
}
File dirFile = new File(sPath);
//如果dir对应的文件不存在,或者不是一个目录,则退出
if (!dirFile.exists() || !dirFile.isDirectory()) {
return false;
}
flag = true;
//删除文件夹下的所有文件(包括子目录)
File[] files = dirFile.listFiles();
for (int i = 0; i < files.length; i++) {
//删除子文件
if (files[i].isFile()) {
flag = deleteFile(files[i].getAbsolutePath());
if (!flag) break;
} //删除子目录
else {
flag = deleteDirectory(files[i].getAbsolutePath());
if (!flag) break;
}
}
if (!flag) return false;
//删除当前目录
if (dirFile.delete()) {
return true;
} else {
return false;
}
}
5、main() 方法
public static void main(String[] args) {
HandleFileClass hfc = new HandleFileClass();
String path = "D:\\test\\folder1\\exam1";
boolean result = hfc.CreateFolder(path);
System.out.println(result);
path = "D:\\test\\folder2";
result = hfc.DeleteFolder(path);
System.out.println(result);
}
B. JAVA 如何创建\删除\修改\复制目录及文件
这需要导入java.io类
1. import java.io.*;
public class FileOperate {
public FileOperate() {
}
public void newFolder(String folderPath) {
try {
String filePath = folderPath;
filePath = filePath.toString();
java.io.File myFilePath = new java.io.File(filePath);
if (!myFilePath.exists()) {
myFilePath.mkdir();
}
}
catch (Exception e) {
System.out.println("新建目录操作出错");
e.printStackTrace();
}
}
2.public void newFile(String filePathAndName, String fileContent) {
try {
String filePath = filePathAndName;
filePath = filePath.toString();
File myFilePath = new File(filePath);
if (!myFilePath.exists()) {
myFilePath.createNewFile();
}
FileWriter resultFile = new FileWriter(myFilePath);
PrintWriter myFile = new PrintWriter(resultFile);
String strContent = fileContent;
myFile.println(strContent);
resultFile.close();
}
catch (Exception e) {
System.out.println("新建目录操作出错");
e.printStackTrace();
}
}
3.删除文件
public void delFile(String filePathAndName) {
try {
String filePath = filePathAndName;
filePath = filePath.toString();
java.io.File myDelFile = new java.io.File(filePath);
myDelFile.delete();
}
catch (Exception e) {
System.out.println("删除文件操作出错");
e.printStackTrace();
}
}
4.public 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) {
System.out.println("删除文件夹操作出错");
e.printStackTrace();
}
}
5.public void delAllFile(String path) {
File file = new File(path);
if (!file.exists()) {
return;
}
if (!file.isDirectory()) {
return;
}
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]);//再删除空文件夹
}
}
}
6.public void File(String oldPath, String newPath) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPath);
if (oldfile.exists()) { //文件存在时
InputStream inStream = new FileInputStream(oldPath); //读入原文件
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1444];
int length;
while ( (byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //字节数 文件大小
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
}
}
catch (Exception e) {
System.out.println("复制单个文件操作出错");
e.printStackTrace();
}
}
6.public void Folder(String oldPath, String newPath) {
try {
(new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
File a=new File(oldPath);
String[] file=a.list();
File temp=null;
for (int i = 0; i < file.length; i++) {
if(oldPath.endsWith(File.separator)){
temp=new File(oldPath+file[i]);
}
else{
temp=new File(oldPath+File.separator+file[i]);
}
if(temp.isFile()){
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(newPath + "/" +
(temp.getName()).toString());
byte[] b = new byte[1024 * 5];
int len;
while ( (len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
}
if(temp.isDirectory()){//如果是子文件夹
Folder(oldPath+"/"+file[i],newPath+"/"+file[i]);
}
}
}
catch (Exception e) {
System.out.println("复制整个文件夹内容操作出错");
e.printStackTrace();
}
}
7.public void moveFile(String oldPath, String newPath) {
File(oldPath, newPath);
delFile(oldPath);
}
public void moveFolder(String oldPath, String newPath) {
Folder(oldPath, newPath);
delFolder(oldPath);
}
}
java中删除目录事先要删除目录下的文件或子目录。用递归就可以实现。
public void del(String filepath) throws IOException{
File f = new File(filepath);//定义文件路径
if(f.exists() && f.isDirectory()){//判断是文件还是目录
if(f.listFiles().length==0){//若目录下没有文件则直接删除
f.delete();
}else{//若有则把文件放进数组,并判断是否有下级目录
File delFile[]=f.listFiles();
int i =f.listFiles().length;
for(int j=0;j<i;j++){
if (delFile[j].isDirectory()){ del (delFile[j].getAbsolutePath());//递归调用del方法并取得子目录路径
}
delFile[j].delete();//删除文件
}
}
del(filepath);//递归调用
}
}
删除一个非空目录并不是简单地创建一个文件对象,然后再调用delete()就可以完成的。要在平台无关的方式下安全地删除一个非空目录,你还需要一个算法。该算法首先删除文件,然后再从目录树的底部由下至上地删除其中所有的目录。
只要简单地在目录中循环查找文件,再调用delete就可以清除目录中的所有文件:
static public void emptyDirectory(File directory) {
File[ ] entries = directory.listFiles( );
for(int i=0; i<entries.length; i++) {
entries[i].delete( );
}
}
这个简单的方法也可以用来删除整个目录结构。当在循环中遇到一个目录时它就递归调用deleteDirectory,而且它也会检查传入的参数是否是一个真正的目录。最后,它将删除作为参数传入的整个目录。
static public void deleteDirectory(File dir) throws IOException {
if( (dir == null) || !dir.isDirectory) {
throw new IllegalArgumentException(
"Argument "+dir+" is not a directory. "
);
}
File[ ] entries = dir.listFiles( );
int sz = entries.length;
for(int i=0; i<sz; i++) {
if(entries[i].isDirectory( )) {
deleteDirectory(entries[i]);
} else {
entries[i].delete( );
}
}
dir.delete();
}
在Java 1.1以及一些J2ME/PersonalJava的变种中没有File.listFiles方法。所以只能用File.list,它的返回值一个字符串数组,你要为每个字符串构造一个新的文件对象。
C. JAVA 如何创建/删除/修改/复制目录及文件
importjava.io.*;
publicclassFileOperate{
publicFileOperate(){
}
/**
*新建目录
*@paramfolderPathString如c:/fqf
*@returnboolean
*/
publicvoidnewFolder(StringfolderPath){
try{
StringfilePath=folderPath;
filePath=filePath.toString();
java.io.FilemyFilePath=newjava.io.File(filePath);
if(!myFilePath.exists()){
myFilePath.mkdir();
}
}
catch(Exceptione){
System.out.println("新建目录操作出错");
e.printStackTrace();
}
}
/**
*新建文件
*@paramfilePathAndNameString文件路径及名称如c:/fqf.txt
*@paramfileContentString文件内容
*@returnboolean
*/
publicvoidnewFile(StringfilePathAndName,StringfileContent){
try{
StringfilePath=filePathAndName;
filePath=filePath.toString();
FilemyFilePath=newFile(filePath);
if(!myFilePath.exists()){
myFilePath.createNewFile();
}
FileWriterresultFile=newFileWriter(myFilePath);
PrintWritermyFile=newPrintWriter(resultFile);
StringstrContent=fileContent;
myFile.println(strContent);
resultFile.close();
}
catch(Exceptione){
System.out.println("新建目录操作出错");
e.printStackTrace();
}
}
/**
*删除文件
*@paramfilePathAndNameString文件路径及名称如c:/fqf.txt
*@paramfileContentString
*@returnboolean
*/
publicvoiddelFile(StringfilePathAndName){
try{
StringfilePath=filePathAndName;
filePath=filePath.toString();
java.io.FilemyDelFile=newjava.io.File(filePath);
myDelFile.delete();
}
catch(Exceptione){
System.out.println("删除文件操作出错");
e.printStackTrace();
}
}
/**
*删除文件夹
*@paramfilePathAndNameString文件夹路径及名称如c:/fqf
*@paramfileContentString
*@returnboolean
*/
publicvoiddelFolder(StringfolderPath){
try{
delAllFile(folderPath);//删除完里面所有内容
StringfilePath=folderPath;
filePath=filePath.toString();
java.io.FilemyFilePath=newjava.io.File(filePath);
myFilePath.delete();//删除空文件夹
}
catch(Exceptione){
System.out.println("删除文件夹操作出错");
e.printStackTrace();
}
}
/**
*删除文件夹里面的所有文件
*@parampathString文件夹路径如c:/fqf
*/
publicvoiddelAllFile(Stringpath){
Filefile=newFile(path);
if(!file.exists()){
return;
}
if(!file.isDirectory()){
return;
}
String[]tempList=file.list();
Filetemp=null;
for(inti=0;i<tempList.length;i++){
if(path.endsWith(File.separator)){
temp=newFile(path+tempList[i]);
}
else{
temp=newFile(path+File.separator+tempList[i]);
}
if(temp.isFile()){
temp.delete();
}
if(temp.isDirectory()){
delAllFile(path+"/"+tempList[i]);//先删除文件夹里面的文件
delFolder(path+"/"+tempList[i]);//再删除空文件夹
}
}
}
/**
*复制单个文件
*@paramoldPathString原文件路径如:c:/fqf.txt
*@paramnewPathString复制后路径如:f:/fqf.txt
*@returnboolean
*/
publicvoidFile(StringoldPath,StringnewPath){
try{
intbytesum=0;
intbyteread=0;
Fileoldfile=newFile(oldPath);
if(oldfile.exists()){//文件存在时
InputStreaminStream=newFileInputStream(oldPath);//读入原文件
FileOutputStreamfs=newFileOutputStream(newPath);
byte[]buffer=newbyte[1444];
intlength;
while((byteread=inStream.read(buffer))!=-1){
bytesum+=byteread;//字节数文件大小
System.out.println(bytesum);
fs.write(buffer,0,byteread);
}
inStream.close();
}
}
catch(Exceptione){
System.out.println("复制单个文件操作出错");
e.printStackTrace();
}
}
/**
*复制整个文件夹内容
*@paramoldPathString原文件路径如:c:/fqf
*@paramnewPathString复制后路径如:f:/fqf/ff
*@returnboolean
*/
publicvoidFolder(StringoldPath,StringnewPath){
try{
(newFile(newPath)).mkdirs();//如果文件夹不存在则建立新文件夹
Filea=newFile(oldPath);
String[]file=a.list();
Filetemp=null;
for(inti=0;i<file.length;i++){
if(oldPath.endsWith(File.separator)){
temp=newFile(oldPath+file[i]);
}
else{
temp=newFile(oldPath+File.separator+file[i]);
}
if(temp.isFile()){
FileInputStreaminput=newFileInputStream(temp);
FileOutputStreamoutput=newFileOutputStream(newPath+"/"+
(temp.getName()).toString());
byte[]b=newbyte[1024*5];
intlen;
while((len=input.read(b))!=-1){
output.write(b,0,len);
}
output.flush();
output.close();
input.close();
}
if(temp.isDirectory()){//如果是子文件夹
Folder(oldPath+"/"+file[i],newPath+"/"+file[i]);
}
}
}
catch(Exceptione){
System.out.println("复制整个文件夹内容操作出错");
e.printStackTrace();
}
}
/**
*移动文件到指定目录
*@paramoldPathString如:c:/fqf.txt
*@paramnewPathString如:d:/fqf.txt
*/
publicvoidmoveFile(StringoldPath,StringnewPath){
File(oldPath,newPath);
delFile(oldPath);
}
/**
*移动文件到指定目录
*@paramoldPathString如:c:/fqf.txt
*@paramnewPathString如:d:/fqf.txt
*/
publicvoidmoveFolder(StringoldPath,StringnewPath){
Folder(oldPath,newPath);
delFolder(oldPath);
}
}
D. Java 怎么 删除有文件的目录
/**
*删除有文件的目录
*
*@author:Sena
*@date:2017-10-30下午3:22:14
*/
publicstaticbooleandeleteDir(Filedir){
if(dir.isDirectory()){
String[]children=dir.list();
//递归删除目录中的子目录下
for(inti=0;i<children.length;i++){
booleansuccess=deleteDir(newFile(dir,children[i]));
if(!success){
returnfalse;
}
}
}
//目录此时为空,可以删除
returndir.delete();
}
E. java中如何删除本地文件夹以及文件
删除文件夹(前提:文件夹为空以及InputStream和OutputStream等一些数据文件流关掉【close()】,否则文件无法删除)
//删除文件夹
publicstaticvoiddelFolder(StringfolderPath){
try{
delAllFile(folderPath);//删除完里面所有内容
StringfilePath=folderPath;
filePath=filePath.toString();
java.io.FilemyFilePath=newjava.io.File(filePath);
myFilePath.delete();//删除空文件夹
}catch(Exceptione){
e.printStackTrace();
}
}
publicstaticbooleandelAllFile(Stringpath){
booleanflag=false;
Filefile=newFile(path);
if(!file.exists()){
returnflag;
}
if(!file.isDirectory()){
returnflag;
}
String[]tempList=file.list();
Filetemp=null;
for(inti=0;i<tempList.length;i++){
if(path.endsWith(File.separator)){
temp=newFile(path+tempList[i]);
}else{
temp=newFile(path+File.separator+tempList[i]);
}
if(temp.isFile()){
temp.delete();
}
if(temp.isDirectory()){
delAllFile(path+"/"+tempList[i]);//先删除文件夹里面的文件
delFolder(path+"/"+tempList[i]);//再删除空文件夹
flag=true;
}
}
returnflag;
}
}
删除指定文件夹下的所有文件
F. java中怎么删除整个文件夹
参考代码如下:
publicstaticvoiddelFolder(StringfolderPath){
try{
//实例化File
java.io.FilemyFilePath=newjava.io.File(filePath);
myFilePath.delete();//删除空文件夹
}catch(Exceptione){
e.printStackTrace();
}
}
G. java删除文件夹怎么删
public boolean deleteDirectory(String sPath) {
//如果sPath不以文件分隔符结尾,自动添加文件分隔符
if (!sPath.endsWith(File.separator)) {
sPath = sPath + File.separator;
}
File dirFile = new File(sPath);
//如果dir对应的文件不存在,或者不是一个目录,则退出
if (!dirFile.exists() || !dirFile.isDirectory()) {
return false;
}
flag = true;
//删除文件夹下的所有文件(包括子目录)
File[] files = dirFile.listFiles();
for (int i = 0; i < files.length; i++) {
//删除子文件
if (files[i].isFile()) {
flag = deleteFile(files[i].getAbsolutePath());
if (!flag) break;
} //删除子目录
else {
flag = deleteDirectory(files[i].getAbsolutePath());
if (!flag) break;
}
}
if (!flag) return false;
//删除当前目录
if (dirFile.delete()) {
return true;
} else {
return false;
}
}
H. Java中如何进行文件(及文件夹)的新建,移动,删除等给出代码
File
F=new
File(路径);/通过将给定路径名字符串转换为抽象路径名来创建一个新
File
实例。
F.delete();//删除此抽象路径名表示的文件或目录。
文件的移动的话,得通过输入输出流
FileInputStream
FI=new
FileInputStream(F);
FileOutputStream
FO=new
FileOutputStream(F);
wile(FI.read()!=EOF)
{
FO.write();
}
I. java 怎么 删除文件夹下的文件
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
public class ReadFile {
public ReadFile() {}
/**
* 删除某个文件夹下的所有文件夹和文件
* @param delpath String
* @throws FileNotFoundException
* @throws IOException
* @return boolean
*/
public static boolean deletefile(String delpath) throws FileNotFoundException,
IOException {
try {
File file = new File(delpath);
if (!file.isDirectory()) {
System.out.println("1");
file.delete();
}
else if (file.isDirectory()) {
System.out.println("2");
String[] filelist = file.list();
for (int i = 0; i < filelist.length; i++) {
File delfile = new File(delpath + "\\" + filelist[i]);
if (!delfile.isDirectory()) {
System.out.println("path=" + delfile.getPath());
System.out.println("absolutepath=" + delfile.getAbsolutePath());
System.out.println("name=" + delfile.getName());
delfile.delete();
System.out.println("删除文件成功");
}
else if (delfile.isDirectory()) {
deletefile(delpath + "\\" + filelist[i]);
}
}
file.delete();
}
}
catch (FileNotFoundException e) {
System.out.println("deletefile() Exception:" + e.getMessage());
}
return true;
}
/**
* 删除某个文件夹下的所有文件夹和文件
* @param delpath String
* @throws FileNotFoundException
* @throws IOException
* @return boolean
*/
public static boolean readfile(String filepath) throws FileNotFoundException,
IOException {
try {
File file = new File(filepath);
if (!file.isDirectory()) {
System.out.println("文件");
System.out.println("path=" + file.getPath());
System.out.println("absolutepath=" + file.getAbsolutePath());
System.out.println("name=" + file.getName());
}
else if (file.isDirectory()) {
System.out.println("文件夹");
String[] filelist = file.list();
for (int i = 0; i < filelist.length; i++) {
File readfile = new File(filepath + "\\" + filelist[i]);
if (!readfile.isDirectory()) {
System.out.println("path=" + readfile.getPath());
System.out.println("absolutepath=" + readfile.getAbsolutePath());
System.out.println("name=" + readfile.getName());
}
else if (readfile.isDirectory()) {
readfile(filepath + "\\" + filelist[i]);
}
}
}
}
catch (FileNotFoundException e) {
System.out.println("readfile() Exception:" + e.getMessage());
}
return true;
}
public static void main(String[] args) {
try {
readfile("D:/file");
//deletefile("D:/file");
}
catch (FileNotFoundException ex) {
}
catch (IOException ex) {
}
System.out.println("ok");
}
}
J. Java如何删除文件夹下的子目录及其包含的子文件
下面给你介绍Java删除文件夹下的子目录及其包含的子文件的方法:
package com.cn.test1;
import java.io.File;
public class DeleteAllFiles {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String filePath = "e:\\fq\\";
System.out.println("开始删除文件");
File file = new File(filePath);
// deleteFile(file);
deleteAllFilesOfDir(file);
System.out.println("删除成功!!");
}
//递归删除文件夹(方法一)
public static void deleteFile(File file) {
if (file.exists()) {//判断文件是否存在
if (file.isFile()) {//判断是否是文件
file.delete();//删除文件
} else if (file.isDirectory()) {//否则如果它是一个目录
File[] files = file.listFiles();//声明目录下所有的文件 files[];
for (int i = 0;i < files.length;i ++) {//遍历目录下所有的文件
deleteFile(files[i]);//把每个文件用这个方法进行迭代
}
file.delete();//删除文件夹
}
} else {
System.out.println("所删除的文件不存在");
}
}
//方法二
public static void deleteAllFilesOfDir(File path) {
if (!path.exists())
return;
if (path.isFile()) {
path.delete();
return;
}
File[] files = path.listFiles();
for (int i = 0; i < files.length; i++) {
deleteAllFilesOfDir(files[i]);
}
path.delete();
}
}