搜尋此網誌

2012年11月8日 星期四

copy file from Android assets folder (由Android的assets資料夾拷貝檔案)

private void copyFile(String source, String destination) {
        InputStream srcStream;
        FileOutputStream desStream;
        try {
            srcStream = this.getResources().getAssets().open(source);
            desStream = new FileOutputStream(new File(destination));
            byte [] data= new byte [1024];
            while (srcStream.read(data) != -1) {
                desStream.write(data);
            }
            srcStream.close();
            desStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } 
add below expression in the AndroidManiFest.xml for getting access permission. 把這行加到AndroidManiFest.xml才有寫入權限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

folder traversal (遞迴搜尋目錄找檔案)

package lang;

import java.io.File;

public class Hello {
    
    public static void main(String[] args){
        
        isFileExisted("." , "Test.java");
            
    
    }
    
    private static boolean isFileExisted(String targetPath , String fileName){
            
            File target = new File(targetPath);
            if(target.isDirectory()){
                File [] files = target.listFiles();
                if(files != null){
                    for(int i = 0 ; i<files.length ; i++){
                        isFileExisted(files[i].getAbsolutePath(), fileName); 
                    }    
                }
                
            }else {
                
                if(fileName.equalsIgnoreCase((target.getName()))){
                    return true;
                }
            }
            return false;
    }
    
}