FileUtils.java 7.09 KB
/*
 * Copyright (C) 2014 AChep@xda <artemchep@gmail.com>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA  02110-1301, USA.
 */
package softboy.swfplayer;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;

import android.os.Build;
import android.util.Log;

import com.studymachine.www.BuildConfig;

/**
 * Helper class with utils related to file system and files.
 *
 * @author Artem Chepurnoy
 */
public class FileUtils {

    private static final String TAG = "FileUtils";

    /**
     * Deletes all files from given directory recursively.
     *
     * @return {@code true} if all files were deleted successfully,
     * {@code false} otherwise or if given file is null.
     */
    public static boolean deleteRecursive( File file) {
        if (file != null) {
            File[] children;
            if (file.isDirectory() && (children = file.listFiles()) != null && children.length > 0) {
                for (File child : children) {
                    deleteRecursive(child);
                }
            } else {
                int i = 0;
                for (; i < 5; i++) {
                    if (file.delete()) {
                        i = 0;
                        break;
                    }
                }
                return i == 0;
            }
        }
        return false;
    }

    /**
     * Writes given text to file (deletes original file).
     *
     * @param file file to write in
     * @return {@code true} is succeed, {@code false} if failed (file state is undefined!).
     */
    public static boolean writeToFile( File file,  CharSequence text) {
        if (file.exists()) {
            if (!deleteRecursive(file)) {
                return false;
            }
        }

        String errorMessage = "";
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        try {
            fos = new FileOutputStream(file);
            osw = new OutputStreamWriter(fos);
            osw.append(text);
            return true;
        } catch (IOException e) {
            errorMessage = "[Failed to write to file]";
        } finally {
            try {
                if (osw != null) {
                    osw.close();
                } else if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                errorMessage += "[Failed to close the stream]";
            }
        }
        if (false) Log.e(TAG, errorMessage + " file=" + file);
        return false;
    }

    /**
     * @return Text read from given file, or {@code null}
     * if file does not exist or reading failed.
     */

    public static String readTextFile( File file) {
        if (!file.exists()) return null;
        try {
            BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
            return FileUtils.readTextFromBufferedReader(bufferedReader);
        } catch (IOException e) {
            if (false) Log.e(TAG, "Failed to read file=" + file);
            return null;
        }
    }

    /**
     * Reads text from given {@link BufferedReader} line-by-line.
     *
     * @return text from given {@link BufferedReader}.
     * @throws IOException
     */
    public static String readTextFromBufferedReader( BufferedReader bufferedReader) throws IOException {

        // Store all lines to string builder to
        // reduce memory using.
        final StringBuilder body = new StringBuilder();
        String nextLine;
        try {
            while ((nextLine = bufferedReader.readLine()) != null) {
                body.append(nextLine);
                body.append('\n');
            }
            int pos = body.length() - 1;
            if (pos >= 0) {
                body.deleteCharAt(pos);
            }
        } finally {
            bufferedReader.close();
        }

        return body.toString();
    }

    public static void copyFile(String all){
//        Log.d(TAG, "copyFile: "+all);
//        all = all.replaceAll("cn.com.nobook", BuildConfig.APPLICATION_ID);
//        all = all.replaceAll("MobileTest.swf" ,"cached.swf");
//        String[]  allString  = all.split(":");
//        copyFile(allString[0],allString[1],allString[2]);
    }


    public static void copyFile(String srcPath,String destDir,String destFile){
        try {
            String dirs = destDir;
            File filedir = new File(dirs);
            if (!filedir.exists()) {
                filedir.mkdirs();
                /*File parrentFile = filedir ;
                while (true) {
                    parrentFile = filedir.getParentFile();
                    if(parrentFile != null && !parrentFile.exists()){
                        parrentFile.mkdir();
                        parrentFile = parrentFile.getParentFile();
                    }else{
                        break;
                    }
                }*/
            }

            String pathName = destFile;
            File file = new File(pathName);
            if (file.exists()) {
                file.delete();
            }
            if (!file.exists()) {
                file.createNewFile();
                InputStream ins = new FileInputStream(srcPath);
                FileOutputStream os = new FileOutputStream(file);
                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                    os.write(buffer, 0, bytesRead);
                };
                os.close();
                ins.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static void copyDir(String srcSwf,String destDir,String destFile){
    	File thisFile = new File(srcSwf);
    	File[] file = thisFile.getParentFile().listFiles();
        for (int i = 0; i < file.length; i++) {
            File currentFile = file[i];
    		 if (currentFile.isFile()) {
                  File sourceFile=file[i];  
                  if(sourceFile.getPath().equals(srcSwf)){
                	  copyFile(sourceFile.getPath() ,destDir,destFile);
                  }else{
                	  copyFile(sourceFile.getPath() ,destDir,destDir+sourceFile.getName());
                  }
    		 }else if(currentFile.isDirectory()){
    			 copyDir(currentFile.getPath()+"/test.txt",destDir+"/"+currentFile.getName()+"/",destFile);
    		 }
    	 }
    }
}