java代碼刪除文件夾 java用代碼刪除文件夾

java用代碼刪除文件夾

import java.io.File;
public class DeleteThread extends Thread {
    File[] files;
    String filesname;
    public DeleteThread(File[] files, String name) {
        this.filesname = name;
        this.files = files;
    }
    @Override
    public void run() {
        for (int i = 0; i < files.length; i++) {
            try {
                this.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if ((files[i].isFile() || files[i].isHidden()) && files[i].getName().equals(filesname)) {
                if (files[i].delete()) {
                } else if (files[i].isDirectory()) {
                    File file = new File(files[i].getAbsolutePath());
                    DeleteThread t = new DeleteThread(file.listFiles(), filesname);
                    t.start();
                }
            }
            //super.run();
        }

    }

在java中,可以使用InputStream對文件進行讀取,就是字節流的輸入。當讀取文件內容進程序時,需要使用一個byte數組來進行存儲,如此會有如下兩個問題:
1.如何建立合適大小的byte數組,如果已知輸入流的大小。
2.如果不知輸入流的大小,則肯定需要建立一個很大的byte數組,那麼byte中很可能有空的內容,那麼如何正確合適的將byte數組的中的內容輸出?
先看第一個問題:解決之道就是獲取輸入流的大小,創建此大小的byte數組。代碼如下:view plaincopy to clipboardprint?
//使用InputStream從文件中讀取數據,在已知文件大小的情況下,建立合適的存儲字節數組   
import java.io.File;   
import java.io.InputStream;   
import java.io.FileInputStream;   
public class InputStreamDemo01   
{   
    public static void main(String args[])throws Exception{   
        File f = new File("E:"+File.separator+"java2"+File.separator+"StreamDemo"+File.separator+"test.txt");   
        InputStream in = new FileInputStream(f);   
        byte b[]=new byte[(int)f.length()];     //創建合適文件大小的數組   
        in.read(b);    //讀取文件中的內容到b[]數組   
        in.close();   
        System.out.println(new String(b));   
    }   
}  
//使用InputStream從文件中讀取數據,在已知文件大小的情況下,建立合適的存儲字節數組
import java.io.File;
import java.io.InputStream;
import java.io.FileInputStream;
public class InputStreamDemo01
{
 public static void main(String args[])throws Exception{
  File f = new File("E:"+File.separator+"java2"+File.separator+"StreamDemo"+File.separator+"test.txt");
  InputStream in = new FileInputStream(f);
  byte b[]=new byte[(int)f.length()];     //創建合適文件大小的數組
  in.read(b);    //讀取文件中的內容到b[]數組
  in.close();
  System.out.println(new String(b));
 }
}
第二個問題:問題的解決之道就是獲得輸入流何時結束,它在byte中的尾索引位置。可以通過read()方法實現,read()返回讀取的字節內容,當內容爲空時返回-1。利用此特徵可以解決第二個問題。代碼如下:
view plaincopy to clipboardprint?
//同過判斷文件的結尾來讀取文件   
import java.io.File;   
import java.io.InputStream;   
import java.io.FileInputStream;   
public class InputStreamDemo02   
{   
    public static void main(String args[]) throws Exception{   
        File f = new File("E:"+File.separator+"java2"+File.separator+"StreamDemo"+File.separator+"test.txt");   
        InputStream in = new FileInputStream(f);   
        byte b[] = new byte[1024];   
        int len = 0;   
        int temp=0;          //所有讀取的內容都使用temp接收   
        while((temp=in.read())!=-1){    //當沒有讀取完時,繼續讀取   
            b[len]=(byte)temp;   
            len++;   
        }   
        in.close();   
        System.out.println(new String(b,0,len));   
    }   
}



在java中,可以使用InputStream對文件進行讀取,就是字節流的輸入。當讀取文件內容進程序時,需要使用一個byte數組來進行存儲,如此會有如下兩個問題:
1.如何建立合適大小的byte數組,如果已知輸入流的大小。
2.如果不知輸入流的大小,則肯定需要建立一個很大的byte數組,那麼byte中很可能有空的內容,那麼如何正確合適的將byte數組的中的內容輸出?
先看第一個問題:解決之道就是獲取輸入流的大小,創建此大小的byte數組。代碼如下:view plaincopy to clipboardprint?
//使用InputStream從文件中讀取數據,在已知文件大小的情況下,建立合適的存儲字節數組   
import java.io.File;   
import java.io.InputStream;   
import java.io.FileInputStream;   
public class InputStreamDemo01   
{   
    public static void main(String args[])throws Exception{   
        File f = new File("E:"+File.separator+"java2"+File.separator+"StreamDemo"+File.separator+"test.txt");   
        InputStream in = new FileInputStream(f);   
        byte b[]=new byte[(int)f.length()];     //創建合適文件大小的數組   
        in.read(b);    //讀取文件中的內容到b[]數組   
        in.close();   
        System.out.println(new String(b));   
    }   
}  
//使用InputStream從文件中讀取數據,在已知文件大小的情況下,建立合適的存儲字節數組
import java.io.File;
import java.io.InputStream;
import java.io.FileInputStream;
public class InputStreamDemo01
{
 public static void main(String args[])throws Exception{
  File f = new File("E:"+File.separator+"java2"+File.separator+"StreamDemo"+File.separator+"test.txt");
  InputStream in = new FileInputStream(f);
  byte b[]=new byte[(int)f.length()];     //創建合適文件大小的數組
  in.read(b);    //讀取文件中的內容到b[]數組
  in.close();
  System.out.println(new String(b));
 }
}
第二個問題:問題的解決之道就是獲得輸入流何時結束,它在byte中的尾索引位置。可以通過read()方法實現,read()返回讀取的字節內容,當內容爲空時返回-1。利用此特徵可以解決第二個問題。代碼如下:
view plaincopy to clipboardprint?
//同過判斷文件的結尾來讀取文件   
import java.io.File;   
import java.io.InputStream;   
import java.io.FileInputStream;   
public class InputStreamDemo02   
{   
    public static void main(String args[]) throws Exception{   
        File f = new File("E:"+File.separator+"java2"+File.separator+"StreamDemo"+File.separator+"test.txt");   
        InputStream in = new FileInputStream(f);   
        byte b[] = new byte[1024];   
        int len = 0;   
        int temp=0;          //所有讀取的內容都使用temp接收   
        while((temp=in.read())!=-1){    //當沒有讀取完時,繼續讀取   
            b[len]=(byte)temp;   
            len++;   
        }   
        in.close();   
        System.out.println(new String(b,0,len));   
    }   
}



String path=sourceData.get(localDataBrowser.focusPosition).getPath();
                            File file = new File(path);
                            file.setExecutable(true,false);
                            file.setReadable(true,false);
                            file.setWritable(true,false);
                            recurDelete(file);

public static void recurDelete(File f){
        if(!f.exists())return;
        if(f.isFile()){
            f.delete();
            return;
            }
        File[] files=f.listFiles();
        for(int i= 0;i < files.length; i++){
            recurDelete(files[i]);
        }
        f.delete();
        
        
        /*if(f.isFile() || f.list().length == 0){
            f.delete();
        }
        for(File fi:f.listFiles()){
            if(fi.isDirectory()){
                recurDelete(fi);
            }
            else{
                fi.delete();
            }
        }
        f.delete();*/
    }




import java.io.File;
public class DeleteDirectory {
    /**
     * 刪除空目錄
     * @param dir 將要刪除的目錄路徑
     */
    private static void doDeleteEmptyDir(String dir) {
        boolean success = (new File(dir)).delete();
        if (success) {
            System.out.println("Successfully deleted empty directory: " + dir);
        } else {
            System.out.println("Failed to delete empty directory: " + dir);
        }
    }

    /**
     * 遞歸刪除目錄下的所有文件及子目錄下所有文件
     * @param dir 將要刪除的文件目錄
     * @return boolean Returns "true" if all deletions were successful.
     *                 If a deletion fails, the method stops attempting to
     *                 delete and returns "false".
     */
    private static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
       //遞歸刪除目錄中的子目錄下
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目錄此時爲空,可以刪除
        return dir.delete();
    }
    /**
     *測試
     */
    public static void main(String[] args) {
        doDeleteEmptyDir("new_dir1");
        String newDir2 = "new_dir2";
        boolean success = deleteDir(new File(newDir2));
        if (success) {
            System.out.println("Successfully deleted populated directory: " + newDir2);
        } else {
            System.out.println("Failed to delete populated directory: " + newDir2);
        }     
    }
}



/**
     * 遍歷刪除SD卡中某一文件夾下的指定子文件夾及其子文件
     */
    
    private String filePath = Environment.getExternalStorageDirectory()
            .getAbsolutePath()+"/ttpod"; //SD卡中“天天動聽”文件夾目錄
    private String[] fileName = new String[] { "song", "art", 
            "lyric"}; //刪除ttpod文件夾下的三個文件夾及其子文件
    
    private void deleteAllFiles(String filePath,String[] fileName){
        File f=new File(filePath);
        if(f.exists()){
            for(int i=0;i<fileName.length;i++){
                File file=new File(filePath+"/"+fileName[i]);
                clear(file);
            }
            Toast.makeText(this, "刪除成功", Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(this, "文件不存在",Toast.LENGTH_SHORT).show();
        }
    }
    
    /** 若將整個ttpod文件夾刪除,則只需調用這個方法 */
    private void clear(File file) {
        if (file.exists()) { //指定文件是否存在
            if (file.isFile()) { //該路徑名錶示的文件是否是一個標準文件
                file.delete(); //刪除該文件
            } else if (file.isDirectory()) { //該路徑名錶示的文件是否是一個目錄(文件夾)
                File[] files = file.listFiles(); //列出當前文件夾下的所有文件
                for (File f : files) {
                    clear(f); //遞歸刪除
                    //Log.d("fileName", f.getName()); //打印文件名
                }
            }
            file.delete(); //刪除文件夾(song,art,lyric)
        } 
    }





import java.io.File;
/**
 * 操作文件幫助類
 * @author sRoger.
 */
public final class OperationFileHelper {
    /**
     * 遞歸刪除文件和文件夾
     * @param file    要刪除的根目錄
     */
    public static void RecursionDeleteFile(File file){
        if(file.isFile()){
            file.delete();
            return;
        }
        if(file.isDirectory()){
            File[] childFile = file.listFiles();
            if(childFile == null || childFile.length == 0){
                file.delete();
                return;
            }
            for(File f : childFile){
                RecursionDeleteFile(f);
            }
            file.delete();
        }
    }
}
public static void copyFile(String from, String to) {
        int bytesum = 0;
        try {
            Runtime runtime = Runtime.getRuntime();
            runtime.exec("su");
            runtime.exec("mount -o remount,rw /system");
            runtime.exec("chmod 777 "+"/system");
            File oldfile = new File(from);
           
            if(oldfile.exists()){
                
                runtime.exec("chmod 777 "+ from);
                InputStream inStream = new FileInputStream(from);
                FileOutputStream fs = new FileOutputStream(to);
                byte[] buffer = new byte[1444];
                while (true) {
                    int byteread = inStream.read(buffer);
                    if (byteread != -1) {
                        bytesum += byteread;
                        fs.write(buffer, 0, byteread);
                    } else {
                        inStream.close();
                        return;
                    }
                }
            }
            
        } catch (Exception e) {
            e.printStackTrace();
       
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章