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();
}
}