diff --git a/build.gradle b/build.gradle index f2b59a5dd73b7f48cbd16e642d995ceab4cefb38..1a0b63a373f365f889d8d442c92ac16160900e41 100644 --- a/build.gradle +++ b/build.gradle @@ -28,10 +28,15 @@ android { } useLibrary 'org.apache.http.legacy' + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } } dependencies { - api 'org.apache.httpcomponents:httpcore:4.4.2' + api 'org.apache.httpcomponents:httpcore:4.4.10' api 'org.greenrobot:eventbus:3.0.0' //compile 'com.loopj.android:android-async-http:1.4.8' diff --git a/src/main/java/com/quseit/base/QBaseApp.java b/src/main/java/com/quseit/base/QBaseApp.java index 7da45080322180abb452bfe9d6763fda231c84bd..07d2bcf09852deba96e6aacf68aa70c3fbe5f58e 100644 --- a/src/main/java/com/quseit/base/QBaseApp.java +++ b/src/main/java/com/quseit/base/QBaseApp.java @@ -5,12 +5,13 @@ import android.content.Context; import com.loopj.android.http.AsyncHttpClient; import com.quseit.config.BASE_CONF; -import com.quseit.util.FileUtils; import java.io.File; import java.util.ArrayList; +import util.FileUtil; + public class QBaseApp { private static final String TAG = "QBaseApp"; @@ -50,7 +51,7 @@ public class QBaseApp { public String getOrCreateRoot(Context context, String subDir) { // String path = Environment.getExternalStorageDirectory().getAbsolutePath()+ (root==null?BASE_CONF.DEFAULT_ROOT:root) // FileUtils.createTestDir(context,"test"); - String path = FileUtils.getQyPath() + (root == null ? BASE_CONF.DEFAULT_ROOT : root) + String path = FileUtil.getQyPath() + (root == null ? BASE_CONF.DEFAULT_ROOT : root) + (subDir != null ? ("/" + subDir) : ""); diff --git a/src/main/java/com/quseit/base/QBaseUpdateService.java b/src/main/java/com/quseit/base/QBaseUpdateService.java index ec7a51060ad4b2810eb08f4a7a84eeb51f367659..c94fef48f69e728506ec2846fdaf93d98343b406 100644 --- a/src/main/java/com/quseit/base/QBaseUpdateService.java +++ b/src/main/java/com/quseit/base/QBaseUpdateService.java @@ -77,7 +77,7 @@ public abstract class QBaseUpdateService extends Service { //创建文件 if (NUtil.isExternalStorageExists()) { try { - updateFile = new File(FileHelper.getBasePath(getApplicationContext(), getDst(), "tmp"), getResources().getString(titleId) + "." + type); + updateFile = new File(FileHelper.getBasePath(/*getApplicationContext(),*/getDst(), "tmp"), getResources().getString(titleId) + "." + type); } catch (NotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); diff --git a/src/main/java/com/quseit/common/CrashHandler.java b/src/main/java/com/quseit/common/CrashHandler.java index 8030234ce8efa1aaf78d69ca87ff0ce07027c02e..a53a44fea4a2c4856955f655134f8351c78e646b 100644 --- a/src/main/java/com/quseit/common/CrashHandler.java +++ b/src/main/java/com/quseit/common/CrashHandler.java @@ -2,7 +2,6 @@ package com.quseit.common; import android.content.Context; import android.os.Build; -import android.os.Environment; import android.os.Looper; import android.util.Log; import android.view.InflateException; @@ -10,7 +9,6 @@ import android.widget.Toast; import com.quseit.android.R; import com.quseit.common.db.AppLog; -import com.quseit.util.FileUtils; import com.quseit.util.NAction; import com.quseit.util.NUtil; diff --git a/src/main/java/com/quseit/util/DocumentsUtils.java b/src/main/java/com/quseit/util/DocumentsUtils.java deleted file mode 100644 index 815d72424247bedde93b52053e89d82572bb7417..0000000000000000000000000000000000000000 --- a/src/main/java/com/quseit/util/DocumentsUtils.java +++ /dev/null @@ -1,510 +0,0 @@ -package com.quseit.util; -//by 乘着船 at 2021-2023 - -import android.annotation.TargetApi; -import android.content.Context; -import android.content.Intent; -import android.content.SharedPreferences; -import android.net.Uri; -import android.os.Build; -import android.os.Environment; -import android.preference.PreferenceManager; -import android.support.v4.provider.DocumentFile; -import android.util.Log; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -public class DocumentsUtils { - - private static final String TAG = DocumentsUtils.class.getSimpleName(); - - //public static final int OPEN_DOCUMENT_TREE_CODE = 8000; - public static final int MAX_BUFFER_SIZE = 5242880;//max buffer size 5MB - - public static final String SDCARD = Environment.getExternalStorageDirectory().getPath(); - public static final String SDCARD_PATH = SDCARD + "/"; - public static final String CONTENT_PRF = "content://"; - public static final String[] SDCARD_CONTENT = new String[]{ - CONTENT_PRF + "com.android.externalstorage.documents/tree/primary%3A", "/document/primary%3A"}; - public static final String ANDROID_PATH = SDCARD_PATH + "Android/"; - public static final String[] ANDROID_CONTENT = new String[]{ - SDCARD_CONTENT[0] + "Android%2F", SDCARD_CONTENT[1] + "Android%2F"}; - - public static final int ANDROID_SAVE_INTENT = - Intent.FLAG_GRANT_READ_URI_PERMISSION | - Intent.FLAG_GRANT_WRITE_URI_PERMISSION ; - public static final int ANDROID_OPEN_INTENT = - Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION | - Intent.FLAG_GRANT_PREFIX_URI_PERMISSION | - ANDROID_SAVE_INTENT ; - - public static List sExtSdCardPaths = new ArrayList<>(); - - //private static String requestRootPath = null; - - private DocumentsUtils() { - - } - - public static void cleanCache() { - sExtSdCardPaths.clear(); - } - - /** - * Get a list of external SD card paths. (Kitkat or higher.) - * - * @return A list of external SD card paths. - */ - @TargetApi(Build.VERSION_CODES.KITKAT) - private static String[] getExtSdCardPaths(Context context) { - if (sExtSdCardPaths.size() > 0) { - return sExtSdCardPaths.toArray(new String[0]); - } - for (File file : context.getExternalFilesDirs("external")) { - if (file != null && !file.equals(context.getExternalFilesDir("external"))) { - int index = file.getAbsolutePath().lastIndexOf("/Android/data"); - if (index < 0) { - Log.d(TAG, "Unexpected external file dir: " + file.getAbsolutePath()); - } else { - String path = file.getAbsolutePath().substring(0, index); - try { - path = new File(path).getCanonicalPath(); - } catch (IOException e) { - // Keep non-canonical path. - } - sExtSdCardPaths.add(path); - } - } - } - if (sExtSdCardPaths.isEmpty()) sExtSdCardPaths.add(SDCARD); - return sExtSdCardPaths.toArray(new String[0]); - } - - /** - * Determine the main folder of the external SD card containing the given file. - * - * @param file the file. - * @return The main folder of the external SD card containing this file, if the file is on an SD - * card. Otherwise, - * null is returned. - */ - @TargetApi(Build.VERSION_CODES.KITKAT) - private static String getExtSdCardFolder(final File file, Context context) { - String[] extSdPaths = getExtSdCardPaths(context); - try { - for (String extSdPath : extSdPaths) { - if (file.getCanonicalPath().startsWith(extSdPath)) { - return extSdPath; - } - } - } catch (IOException e) { - return null; - } - return null; - } - - /** - * Determine if a file is on external sd card. (Kitkat or higher.) - * - * @param file The file. - * @return true if on external sd card. - */ - @TargetApi(Build.VERSION_CODES.KITKAT) - public static boolean isOnExtSdCard(final File file, Context c) { - return getExtSdCardFolder(file, c) != null; - } - - /** - * Get a DocumentFile corresponding to the given file (for writing on ExtSdCard on Android 5). - * If the file is not - * existing, it is created. - * - * @param file The file. - * @param isDirectory true/false/null - * true/false - flag indicating if the file should be a directory , - * if file not exist, it will be create . - * null - do not know the file is a directory , - * if file not exist, it will not be create . - * @return The DocumentFile - */ - public static DocumentFile getDocumentFile( - final File file, final Boolean isDirectory, Context context) { - - String baseFolder = getExtSdCardFolder(file, context); - boolean originalDirectory = false; - if (baseFolder == null) { - return null; - } - - String relativePath = null; - try { - String fullPath = file.getCanonicalPath(); - if (!baseFolder.equals(fullPath)) { - relativePath = fullPath.substring(baseFolder.length() + 1); - } else { - originalDirectory = true; - } - } catch (IOException e) { - return null; - } catch (Exception f) { - originalDirectory = true; - //continue - } - String as = PreferenceManager.getDefaultSharedPreferences(context).getString(baseFolder, - null); - - Uri treeUri = null; - if (as != null) treeUri = Uri.parse(as); - if (treeUri == null) { - return null; - } - - // start with root of SD card and then parse through document tree. - DocumentFile document = DocumentFile.fromTreeUri(context, treeUri); - if (originalDirectory) return document; - String[] parts = relativePath.split("/"); - for (int i = 0; i < parts.length; i++) { - DocumentFile nextDocument = document.findFile(parts[i]); - - if (nextDocument == null) { - if(isDirectory == null) return null; - if ((i < parts.length - 1) || isDirectory) { - nextDocument = document.createDirectory(parts[i]); - } else { - nextDocument = document.createFile("image", parts[i]); - } - } - document = nextDocument; - } - - return document; - } - - public static boolean mkdirs(Context context, File dir) { - boolean res = dir.mkdirs(); - if (!res) { - if (isOnExtSdCard(dir, context)) { - DocumentFile documentFile = getDocumentFile(dir, true, context); - res = documentFile != null && documentFile.canWrite(); - } - } - return res; - } - - private static boolean FileDelete(File file) { - if (file.isFile()) return file.delete(); - File[] subFiles = file.listFiles(); - if (subFiles==null || subFiles.length==0) - return file.delete(); - boolean ret = true; - for(File subFile:subFiles){ - if (subFile.isDirectory()) ret = FileDelete(subFile) && ret; - else ret = subFile.delete() && ret; - } - return ret && file.delete(); - } - - public static boolean delete(Context context, File file) { - boolean ret = FileDelete(file); - if (ret) return ret; - //if (isOnExtSdCard(file, context)) { - DocumentFile f = getDocumentFile(file, false, context); - if (f != null) { - ret = f.delete(); - } - //} - return ret; - } - - public static boolean canWrite(File file) { - boolean res = file.exists() && file.canWrite(); - - if (!res && !file.exists()) { - try { - if (!file.isDirectory()) { - res = file.createNewFile() && file.delete(); - } else { - res = file.mkdirs() && file.delete(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - return res; - } - - /*public static boolean canWrite(Context context, File file) { - boolean res = canWrite(file); - - if (!res && isOnExtSdCard(file, context)) { - DocumentFile documentFile = getDocumentFile(file, true, context); - res = documentFile != null && documentFile.canWrite(); - } - return res; - }*/ - - private static boolean renameToCross(Context context,File src,File dest) throws Exception { - copy(context,src,dest); - boolean exist = dest.exists(); - if (!exist) { - DocumentFile Dest = getDocumentFile(dest,null,context); - if(Dest!=null && Dest.exists()) - exist = true; - } - delete(context,src); - return exist; - } - - public static boolean renameTo(Context context, File src, File dest) throws Exception { - boolean res = src.renameTo(dest); - if (res) return true; - - if (isOnExtSdCard(dest, context)) { - DocumentFile srcDoc; - if (isOnExtSdCard(src, context)) { - srcDoc = getDocumentFile(src, false, context); - } else { - srcDoc = DocumentFile.fromFile(src); - } - DocumentFile destDoc = getDocumentFile(dest.getParentFile(), true, context); - - if (srcDoc != null && destDoc != null) { - if(!srcDoc.exists()) - throw new FileNotFoundException(src.toString()); - if (Objects.equals(src.getParent(), dest.getParent())) { - DocumentFile DestDoc = getDocumentFile(dest, null, context); - if(DestDoc!=null && DestDoc.exists()){ - if(!DestDoc.delete()) - return false; - } - res = srcDoc.renameTo(dest.getName()); - }/* else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - DocumentFile srcParentDoc = srcDoc.getParentFile(); - if (srcParentDoc!=null) { - res = DocumentsContract.moveDocument(context.getContentResolver(), - srcDoc.getUri(), - srcParentDoc.getUri(), - destDoc.getUri()) != null; - }*/ else return renameToCross(context, src, dest); - //} - } else { - if ((src.exists() || srcDoc!=null) && (dest.canWrite() || destDoc!=null)) - return renameToCross(context, src, dest); - else return false; - } - } else return renameToCross(context, src, dest); - - return res; - } - - public static InputStream getInputStream(Context context, File destFile) { - InputStream in = null; - try { - if (!canWrite(destFile) && isOnExtSdCard(destFile, context)) { - DocumentFile file = getDocumentFile(destFile, false, context); - if (file != null && file.canWrite()) { - in = context.getContentResolver().openInputStream(file.getUri()); - } - } else { - in = new FileInputStream(destFile); - - } - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - return in; - } - - public static OutputStream getOutputStream(Context context, File destFile) { - OutputStream out = null; - try { - if (!canWrite(destFile) && isOnExtSdCard(destFile, context)) { - DocumentFile file = getDocumentFile(destFile, false, context); - if (file != null && file.canWrite()) - out = context.getContentResolver().openOutputStream(file.getUri(),"wt"); - } else { - out = new FileOutputStream(destFile); - - } - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - return out; - } - - public static void saveTreeUri(Context context, String rootPath, Uri uri) { - DocumentFile file = DocumentFile.fromTreeUri(context, uri); - if (file != null && file.canWrite()) { - SharedPreferences perf = PreferenceManager.getDefaultSharedPreferences(context); - perf.edit().putString(rootPath, uri.toString()).apply(); - } else { - Log.e(TAG, "no write permission: " + rootPath); - } - } - - /*public static boolean checkWritableRootPath(Context context, String rootPath) { - File root = new File(rootPath); - if (!root.canWrite()) { - - if (isOnExtSdCard(root, context)) { - DocumentFile documentFile = getDocumentFile(root, true, context); - return documentFile == null || !documentFile.canWrite(); - } else { - SharedPreferences perf = PreferenceManager.getDefaultSharedPreferences(context); - - String documentUri = perf.getString(rootPath, ""); - - if (documentUri == null || documentUri.isEmpty()) { - return true; - } else { - DocumentFile file = DocumentFile.fromTreeUri(context, Uri.parse(documentUri)); - return !(file != null && file.canWrite()); - } - } - } - return false; - }*/ - - private static void copyFile ( - Context context, File srcFile, File destFile) throws Exception { - InputStream fis=getInputStream(context,srcFile); - if (fis==null) fis=new FileInputStream(srcFile); - OutputStream fos=getOutputStream(context,destFile); - if (fos==null) fos=new FileOutputStream(destFile); - int len = fis.available(); - if (len>MAX_BUFFER_SIZE) len=MAX_BUFFER_SIZE; - byte[] flush =new byte [len]; - while((len=fis.read(flush))>0) { - fos.write(flush,0,len); - } - fos.flush(); - fis.close(); - fos.close(); - } - - private static void copyTree ( - Context context,File srcFolder,File destFolder) - throws Exception{ - DocumentFile DestFolder=getDocumentFile(destFolder,true,context); - if (DestFolder==null) destFolder.mkdirs(); - DocumentFile SrcFolder=getDocumentFile(srcFolder,true,context); - String name; - File srcSub,destSub; - if (SrcFolder != null) { - DocumentFile[] SrcSubs = SrcFolder.listFiles(); - for(DocumentFile SrcSub:SrcSubs) { - name = SrcSub.getName(); - srcSub=new File(srcFolder.getAbsolutePath(), name); - destSub=new File(destFolder.getAbsolutePath(), name); - if (SrcSub.isDirectory()){ - copyTree(context,srcSub,destSub); - } else { - copyFile(context,srcSub,destSub); - } - } - } else { - File[] SrcSubs = srcFolder.listFiles(); - for(File SrcSub:SrcSubs) { - name = SrcSub.getName(); - srcSub=new File(srcFolder.getAbsolutePath(), name); - destSub=new File(destFolder.getAbsolutePath(), name); - if (SrcSub.isDirectory()){ - copyTree(context,srcSub,destSub); - } else { - copyFile(context,srcSub,destSub); - } - } - } - } - - public static void copy ( - Context context, File src, File dest) - throws Exception{ - if (isDirectory(context,src)) - copyTree(context,src,dest); - else copyFile(context,src,dest); - } - - public static String[] listFiles ( - Context context,File folder) - throws Exception{ - DocumentFile Folder=getDocumentFile(folder,true,context); - if (Folder == null) { - File[] Subs = folder.listFiles(); - if (Subs==null) return null; - String[] subs=new String[Subs.length]; - for (int i=0;i typeFiles; - - public static final void createDirIfNExists(String dirname) { - File yy = new File(dirname); - if (!yy.exists()) { - yy.mkdirs(); - } - } - - public static final void createFileFromAssetsIfNExists(Context con, String filename, String dst) { - File yy = new File(dst); - if (!yy.exists()) { - String content = FileHelper.LoadDataFromAssets(con, filename); - FileHelper.writeToFile(dst, content); - } - } - - public static void openFile(Context context, String filePath, String fileExtension) { - Intent intent = new Intent(); - intent.setAction(android.content.Intent.ACTION_VIEW); - File file = new File(filePath); - MimeTypeMap mime = MimeTypeMap.getSingleton(); - String type = mime.getMimeTypeFromExtension(fileExtension); - intent.setDataAndType(Uri.fromFile(file), type); - intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - try { - context.startActivity(intent); - } catch (android.content.ActivityNotFoundException e) { - } - } - - public static String getFileNameFromUrl(String urlFile) { - try { - URL url = new URL(urlFile); - File f = new File(url.getPath()); - return f.getName(); - - } catch (MalformedURLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - - return "unname.dat"; - } - } - - public static String getTypeByMimeType(String mType) { - if (mType.equals("application/vnd.android.package-archive")) { - return "apk"; - } else { - String[] xx = mType.split("/"); - if (xx.length > 1) { - return xx[0]; - } - } - return "other"; - } - - public static String LoadDataFromAssets(Context context, String inFile) { - String tContents = ""; - - try { - InputStream stream = context.getAssets().open(inFile); - int size = stream.available(); - byte[] buffer = new byte[size]; - stream.read(buffer); - stream.close(); - tContents = new String(buffer); - } catch (IOException e) { - } - return tContents; - } - - public static void putFileContents(Context context, String filename, String content) { - try { - File fileCache = new File(filename); - byte[] data = content.getBytes(); - FileOutputStream outStream; - outStream = new FileOutputStream(fileCache); - outStream.write(data); - outStream.close(); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - - } - } - - public static void writeToFile(String filePath, String data) { - try { - File file = new File(filePath); - if (!file.exists()) { - if (!file.createNewFile()) { - return; - } - } - - FileOutputStream fOut = new FileOutputStream(filePath); - fOut.write(data.getBytes()); - fOut.flush(); - fOut.close(); - } catch (IOException iox) { - iox.printStackTrace(); - } - - } - - public static String getFileContentsFromAssets(Context context, String filename) { - String content = ""; //结果字符串 - try { - java.io.InputStream is = context.getResources().getAssets().open(filename); //打开文件 - int ch = 0; - ByteArrayOutputStream baos = new ByteArrayOutputStream(); //实现了一个输出流 - while ((ch = is.read()) != -1) { - baos.write(ch); //将指定的字节写入此 byte 数组输出流 - } - byte[] buff = baos.toByteArray();//以byte 数组的形式返回此输出流的当前内容 - baos.close(); //关闭流 - is.close(); //关闭流 - content = new String(buff, "UTF-8"); //设置字符串编码 - - } catch (Exception e) { - e.printStackTrace(); - //Log.d(TAG, "getFileContentsFromAssets:"+e.getMessage()); - } - return content; - } - - public static String getFileContents(String filename, int pos) { - - File scriptFile = new File(filename); - String tContent = ""; - if (scriptFile.exists()) { - BufferedReader in; - try { - in = new BufferedReader(new FileReader(scriptFile)); - String line; - - while ((line = in.readLine()) != null) { - tContent += line + "\n"; - if (tContent.length() >= pos) { - in.close(); - return tContent; - } - } - in.close(); - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } - return tContent; - } - - public static String getFileContents(String filename) { - File scriptFile = new File(filename); - String tContent = ""; - if (scriptFile.exists()) { - BufferedReader in; - try { - in = new BufferedReader(new FileReader(scriptFile)); - String line; - - while ((line = in.readLine()) != null) { - tContent += line + "\n"; - } - in.close(); - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } - return tContent; - } - - public static void clearDir(String dir, int level, boolean deleteS) { - //Log.d(TAG, "clearDir:"+dir); - File basePath = new File(dir); - if (basePath.exists() && basePath.isDirectory()) { - for (File item : basePath.listFiles()) { - if (item.isFile()) { - //Log.d(TAG, "deleteItem:"+item.getAbsolutePath()); - item.delete(); - - } else if (item.isDirectory()) { - clearDir(item.getAbsolutePath(), level + 1, deleteS); - } - } - if (level > 0 || deleteS) { - basePath.delete(); - } - } else if (basePath.exists()) { - basePath.delete(); - } - } - - public static File getBasePath(Context context, String parDir, String subdir) throws IOException { - try { -// File basePath = new File(Environment.getExternalStorageDirectory(), -// FileUtils.createTestDir(context,"test"); - File basePath = new File(FileUtils.getQyPath(), - parDir); - - if (!basePath.exists()) { - if (!basePath.mkdirs()) { - throw new IOException(String.format("%s cannot be created!", - basePath.toString())); - } - } - File subPath = null; - if (!subdir.equals("")) { -// subPath = new File(Environment.getExternalStorageDirectory(), -// FileUtils.createTestDir(context,"test"); - subPath = new File(FileUtils.getQyPath(), - parDir + "/" + subdir); - if (!subPath.exists()) { - if (!subPath.mkdirs()) { - throw new IOException(String.format("%s cannot be created!", - subPath.toString())); - } - } - } - - if (!basePath.isDirectory()) { - throw new IOException(String.format("%s is not a directory!", - basePath.toString())); - } - if (subdir.equals("")) { - return basePath; - } else { - return subPath; - } - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - /*public static File getBasePath(String subdir) throws IOException { - File basePath = new File(Environment.getExternalStorageDirectory(), - BASE_CONF.BASE_PATH); - - if (!basePath.exists()) { - if (!basePath.mkdirs()) { - throw new IOException(String.format("%s cannot be created!", - basePath.toString())); - } - } - File subPath = null; - if (!subdir.equals("")) { - subPath = new File(Environment.getExternalStorageDirectory(), - BASE_CONF.BASE_PATH+"/"+subdir); - if (!subPath.exists()) { - if (!subPath.mkdirs()) { - throw new IOException(String.format("%s cannot be created!", - subPath.toString())); - } - } - } - - if (!basePath.isDirectory()) { - throw new IOException(String.format("%s is not a directory!", - basePath.toString())); - } - if (subdir.equals("")) - return basePath; - else - return subPath; - } - */ - public static File getABSPath(String subdir) throws IOException { - File basePath = new File(subdir); - - if (!basePath.exists()) { - if (!basePath.mkdirs()) { - throw new IOException(String.format("%s cannot be created!", - basePath.toString())); - } - } - File subPath = null; - if (!subdir.equals("")) { - subPath = new File(subdir); - if (!subPath.exists()) { - if (!subPath.mkdirs()) { - throw new IOException(String.format("%s cannot be created!", - subPath.toString())); - } - } - } - - if (!basePath.isDirectory()) { - throw new IOException(String.format("%s is not a directory!", - basePath.toString())); - } - if (subdir.equals("")) { - return basePath; - } else { - return subPath; - } - } - - public static String getFileName(String filename) { - File f = new File(filename); - return f.getName(); - } - - public static String getExt(String filename, String def) { - String[] yy = filename.split("\\?"); - String[] xx = yy[0].split("\\."); - //Log.d(TAG, "filename:"+filename+"-size:"+xx.length); - - if (xx.length < 2) { - return def; - } else { - String ext = xx[xx.length - 1]; - //Log.d(TAG, "ext:"+ext); - return ext; - } - } - - public static JSONObject getUrlAsJO(String link) { - try { - // get URL content - URL url = new URL(link); - URLConnection conn = url.openConnection(); - - // open the stream and put it into BufferedReader - BufferedReader br = new BufferedReader( - new InputStreamReader(conn.getInputStream())); - - String inputLine; - - - String ret = ""; - - while ((inputLine = br.readLine()) != null) { - ret = ret + inputLine + "\n"; - } - - br.close(); - - try { - return new JSONObject(ret.trim()); - } catch (JSONException e) { - return null; - } - //System.out.println("Done"); - } catch (IOException e) { - e.printStackTrace(); - } - return null; - - } - - - public static boolean getUrlAsFile(String link, String fileName) { - try { - // get URL content - URL url = new URL(link); - URLConnection conn = url.openConnection(); - - // open the stream and put it into BufferedReader - BufferedReader br = new BufferedReader( - new InputStreamReader(conn.getInputStream())); - - String inputLine; - - //save to this filename - File file = new File(fileName); - - if (!file.exists()) { - file.createNewFile(); - } - - //use FileWriter to write file - FileWriter fw = new FileWriter(file.getAbsoluteFile()); - BufferedWriter bw = new BufferedWriter(fw); - - while ((inputLine = br.readLine()) != null) { - bw.write(inputLine + "\n"); - } - - bw.close(); - br.close(); - - //System.out.println("Done"); - return true; - } catch (IOException e) { - e.printStackTrace(); - } - return false; - - } - - /** - * @param dir - * @return The first file to be found in dir - */ - public static File getFileByType(File dir) { - File[] files = dir.listFiles(); - for (File file : files) { - if (file.isDirectory() && !file.getAbsolutePath().contains("/.")) { - getFileByType(file); - } else if (file.getName().equals("main.py")) { - return file; - } else if (file.getName().contains(".py")) { - return file; - } - } - return null; - } - - /** - * @param dir - * @return The main file to be found in dir - */ - public static File getMainFileByType(File dir) { - File xx = new File(dir.getAbsolutePath() + "/main.py"); - return xx.exists() ? xx : null; - } - - /** - * Filter Files by type - * - * @param dir - * @return - */ - public static File[] getFilesByType(File dir) { - if (dir == null) { - return null; - } - typeFiles = new ArrayList<>(); - addFile(dir); - return typeFiles.toArray(new File[0]); - } - - private static void addFile(File dir) { - File[] dirFiles = dir.listFiles(); - if (dirFiles != null) { - for (File file : dirFiles) { - if (file.isDirectory() && !file.getAbsolutePath().contains("/.")) { - addFile(file); - } else if (file.getName().contains(".py") && !file.getName().substring(0, 1).equals(".")) { - typeFiles.add(file); - } - } - } - } - - public static void copyFile(File file, String outputPath) { - int BUFFER_SIZE = 4069; - try { - InputStream inputStream = new FileInputStream(file); - OutputStream outputStream = new FileOutputStream(outputPath); - - byte[] buffer = new byte[BUFFER_SIZE]; - int bytesRead; - - while ((bytesRead = inputStream.read(buffer)) != -1) { - outputStream.write(buffer, 0, bytesRead); - } - } catch (IOException ex) { - ex.printStackTrace(); - } - } - - public static void moveFile(File file, String outputPath) { - if (file.isDirectory()) { - for (File file1 : file.listFiles()) { - moveFile(file1, outputPath); - } - file.delete(); - } else { - copyFile(file, outputPath + "/" + file.getName()); - file.delete(); - } - } - - /** - * @param file root file - * @return all sub-file except dir file and hided file(start with '.') - */ - public static List filterDir(File file) { - List files = new ArrayList<>(); - File[] subFile = file.listFiles(); - if (subFile != null) { - for (File file1 : subFile) { - if (!file1.isDirectory()) { - files.add(file1); - } else if (!file1.getName().startsWith(".")) { - files.addAll(filterDir(file1)); - } - } - } - return files; - } - - - public static List filterExt(File dir, String[] exts, int size) { - List filtered = new ArrayList<>(); - List files = filterDir(dir); - for (File file : files) { - if (file.getName().startsWith(".")) { - continue; - } - String ext = ""; - if (file.getName().lastIndexOf(".") > 0) { - ext = file.getName().substring(file.getName().lastIndexOf(".") + 1); - } - for (String s : exts) { - if (s.equals(ext)) { - filtered.add(file); - size += 1; - } - } - } - return filtered; - } - - public static List filterExt(File dir, String[] exts) { - List filtered = new ArrayList<>(); - List files = filterDir(dir); - for (File file : files) { - if (file.getName().startsWith(".")) { - continue; - } - String ext = ""; - if (file.getName().lastIndexOf(".") > 0) { - ext = file.getName().substring(file.getName().lastIndexOf(".") + 1); - } - for (String s : exts) { - if (s.equals(ext)) { - filtered.add(file); - } - } - } - return filtered; - } - - public static File findFile(File dir, String findName) { - File result = null; - if (dir.isDirectory()) { - for (File file : dir.listFiles()) { - if (file.isDirectory()) { - File ret = findFile(file, findName); - if (ret != null) { - result = ret; - } - } else { - if (file.getName().equals(findName)) { - result = file; - } - } - } - return result; - } else { - return dir; - } - } -} +package com.quseit.util; + +import android.content.Context; +import android.content.Intent; +import android.net.Uri; +import android.os.Environment; +import android.webkit.MimeTypeMap; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.util.ArrayList; +import java.util.List; + +/** + * 对SD卡文件的管理 + * + * @author ch.linghu + */ +public class FileHelper { + @SuppressWarnings("unused") + private static final String TAG = "FileHelper"; + private static List typeFiles; + + public static final void createDirIfNExists(String dirname) { + File yy = new File(dirname); + if (!yy.exists()) { + yy.mkdirs(); + } + } + + public static final void createFileFromAssetsIfNExists(Context con, String filename, String dst) { + File yy = new File(dst); + if (!yy.exists()) { + String content = FileHelper.LoadDataFromAssets(con, filename); + FileHelper.writeToFile(dst, content); + } + } + + public static void openFile(Context context, String filePath, String fileExtension) { + Intent intent = new Intent(); + intent.setAction(Intent.ACTION_VIEW); + File file = new File(filePath); + MimeTypeMap mime = MimeTypeMap.getSingleton(); + String type = mime.getMimeTypeFromExtension(fileExtension); + intent.setDataAndType(Uri.fromFile(file), type); + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + try { + context.startActivity(intent); + } catch (android.content.ActivityNotFoundException e) { + } + } + + public static String getFileNameFromUrl(String urlFile) { + try { + URL url = new URL(urlFile); + File f = new File(url.getPath()); + return f.getName(); + + } catch (MalformedURLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + + return "unname.dat"; + } + } + + public static String getTypeByMimeType(String mType) { + if (mType.equals("application/vnd.android.package-archive")) { + return "apk"; + } else { + String[] xx = mType.split("/"); + if (xx.length > 1) { + return xx[0]; + } + } + return "other"; + } + + public static String LoadDataFromAssets(Context context, String inFile) { + String tContents = ""; + + try { + InputStream stream = context.getAssets().open(inFile); + int size = stream.available(); + byte[] buffer = new byte[size]; + stream.read(buffer); + stream.close(); + tContents = new String(buffer); + } catch (IOException e) { + } + return tContents; + } + + public static void putFileContents(String filename, String content) { + try { + File fileCache = new File(filename); + byte[] data = content.getBytes(); + FileOutputStream outStream; + outStream = new FileOutputStream(fileCache); + outStream.write(data); + outStream.close(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + + } + } + + public static void writeToFile(String filePath, String data) { + try { + File file = new File(filePath); + if (!file.exists()) { + if (!file.createNewFile()) { + return; + } + } + + FileOutputStream fOut = new FileOutputStream(filePath); + fOut.write(data.getBytes()); + fOut.flush(); + fOut.close(); + } catch (IOException iox) { + iox.printStackTrace(); + } + + } + + public static String getFileContentsFromAssets(Context context, String filename) { + String content = ""; //结果字符串 + try { + InputStream is = context.getResources().getAssets().open(filename); //打开文件 + int ch = 0; + ByteArrayOutputStream baos = new ByteArrayOutputStream(); //实现了一个输出流 + while ((ch = is.read()) != -1) { + baos.write(ch); //将指定的字节写入此 byte 数组输出流 + } + byte[] buff = baos.toByteArray();//以byte 数组的形式返回此输出流的当前内容 + baos.close(); //关闭流 + is.close(); //关闭流 + content = new String(buff, "UTF-8"); //设置字符串编码 + + } catch (Exception e) { + e.printStackTrace(); + //Log.d(TAG, "getFileContentsFromAssets:"+e.getMessage()); + } + return content; + } + + public static String getFileContents(String filename, int pos) { + + File scriptFile = new File(filename); + StringBuilder tContent = new StringBuilder(); + if (scriptFile.exists()) { + BufferedReader in; + try { + in = new BufferedReader(new FileReader(scriptFile)); + String line; + + while ((line = in.readLine()) != null) { + tContent.append(line).append("\n"); + if (tContent.length() >= pos) { + in.close(); + return tContent.toString(); + } + } + in.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + return tContent.toString(); + } + + public static String getFileContent(String filename) { + File scriptFile = new File(filename); + StringBuilder tContent = new StringBuilder(); + if (scriptFile.exists()) { + BufferedReader in; + try { + in = new BufferedReader(new FileReader(scriptFile)); + String line; + + int off = 0;int len = 0; + char[] buf = new char[100]; + while ((len = in.read(buf,off,100)) == 100) { + tContent.append(buf); + } + tContent.append(buf,0,len); + in.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + return tContent.toString(); + } + + public static String getFileContents(String filename) { + File scriptFile = new File(filename); + StringBuilder tContent = new StringBuilder(); + if (scriptFile.exists()) { + BufferedReader in; + try { + in = new BufferedReader(new FileReader(scriptFile)); + String line; + + while ((line = in.readLine()) != null) { + tContent.append(line).append("\n"); + } + in.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + return tContent.toString(); + } + + public static String getFileContents(File scriptFile) { + StringBuilder tContent = new StringBuilder(); + if (scriptFile.exists()) { + BufferedReader in; + try { + in = new BufferedReader(new FileReader(scriptFile)); + String line; + + while ((line = in.readLine()) != null) { + tContent.append(line).append("\n"); + } + in.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + return tContent.toString(); + } + + public static void clearDir(String dir, int level, boolean deleteS) { + //Log.d(TAG, "clearDir:"+dir); + File basePath = new File(dir); + if (basePath.exists() && basePath.isDirectory()) { + for (File item : basePath.listFiles()) { + if (item.isFile()) { + //Log.d(TAG, "deleteItem:"+item.getAbsolutePath()); + item.delete(); + + } else if (item.isDirectory()) { + clearDir(item.getAbsolutePath(), level + 1, deleteS); + } + } + if (level > 0 || deleteS) { + basePath.delete(); + } + } else if (basePath.exists()) { + basePath.delete(); + } + } + + public static File getBasePath(String parDir, String subdir) throws IOException { + try { + File basePath = new File(Environment.getExternalStorageDirectory(), + parDir); + + if (!basePath.exists()) { + if (!basePath.mkdirs()) { + throw new IOException(String.format("%s cannot be created!", + basePath.toString())); + } + } + File subPath = null; + if (!subdir.equals("")) { + subPath = new File(Environment.getExternalStorageDirectory(), + parDir + "/" + subdir); + if (!subPath.exists()) { + if (!subPath.mkdirs()) { + throw new IOException(String.format("%s cannot be created!", + subPath.toString())); + } + } + } + + if (!basePath.isDirectory()) { + throw new IOException(String.format("%s is not a directory!", + basePath.toString())); + } + if (subdir.equals("")) + return basePath; + else + return subPath; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /*public static File getBasePath(String subdir) throws IOException { + File basePath = new File(Environment.getExternalStorageDirectory(), + BASE_CONF.BASE_PATH); + + if (!basePath.exists()) { + if (!basePath.mkdirs()) { + throw new IOException(String.format("%s cannot be created!", + basePath.toString())); + } + } + File subPath = null; + if (!subdir.equals("")) { + subPath = new File(Environment.getExternalStorageDirectory(), + BASE_CONF.BASE_PATH+"/"+subdir); + if (!subPath.exists()) { + if (!subPath.mkdirs()) { + throw new IOException(String.format("%s cannot be created!", + subPath.toString())); + } + } + } + + if (!basePath.isDirectory()) { + throw new IOException(String.format("%s is not a directory!", + basePath.toString())); + } + if (subdir.equals("")) + return basePath; + else + return subPath; + } + */ + public static File getABSPath(String subdir) throws IOException { + File basePath = new File(subdir); + + if (!basePath.exists()) { + if (!basePath.mkdirs()) { + throw new IOException(String.format("%s cannot be created!", + basePath.toString())); + } + } + File subPath = null; + if (!subdir.equals("")) { + subPath = new File(subdir); + if (!subPath.exists()) { + if (!subPath.mkdirs()) { + throw new IOException(String.format("%s cannot be created!", + subPath.toString())); + } + } + } + + if (!basePath.isDirectory()) { + throw new IOException(String.format("%s is not a directory!", + basePath.toString())); + } + if (subdir.equals("")) + return basePath; + else + return subPath; + } + + public static String getFileName(String filename) { + File f = new File(filename); + return f.getName(); + } + + public static String getExt(String filename, String def) { + String[] yy = filename.split("\\?"); + String[] xx = yy[0].split("\\."); + //Log.d(TAG, "filename:"+filename+"-size:"+xx.length); + + if (xx.length < 2) { + return def; + } else { + String ext = xx[xx.length - 1]; + //Log.d(TAG, "ext:"+ext); + return ext; + } + } + + public static JSONObject getUrlAsJO(String link) { + try { + // get URL content + URL url = new URL(link); + URLConnection conn = url.openConnection(); + + // open the stream and put it into BufferedReader + BufferedReader br = new BufferedReader( + new InputStreamReader(conn.getInputStream())); + + String inputLine; + + + String ret = ""; + + while ((inputLine = br.readLine()) != null) { + ret = ret + inputLine + "\n"; + } + + br.close(); + + try { + return new JSONObject(ret.trim()); + } catch (JSONException e) { + return null; + } + //System.out.println("Done"); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + + } + + + public static boolean getUrlAsFile(String link, String fileName) { + try { + // get URL content + URL url = new URL(link); + URLConnection conn = url.openConnection(); + + // open the stream and put it into BufferedReader + BufferedReader br = new BufferedReader( + new InputStreamReader(conn.getInputStream())); + + String inputLine; + + //save to this filename + File file = new File(fileName); + + if (!file.exists()) { + file.createNewFile(); + } + + //use FileWriter to write file + FileWriter fw = new FileWriter(file.getAbsoluteFile()); + BufferedWriter bw = new BufferedWriter(fw); + + while ((inputLine = br.readLine()) != null) { + bw.write(inputLine + "\n"); + } + + bw.close(); + br.close(); + + //System.out.println("Done"); + return true; + } catch (IOException e) { + e.printStackTrace(); + } + return false; + + } + + /** + * @param dir + * @return The first file to be found in dir + */ + public static File getFileByType(File dir) { + File[] files = dir.listFiles(); + for (File file : files) { + if (file.isDirectory() && !file.getAbsolutePath().contains("/.")) { + getFileByType(file); + } else if (file.getName().equals("main.py")) { + return file; + } else if (file.getName().contains(".py")) { + return file; + } + } + return null; + } + + /** + * @param dir + * @return The main file to be found in dir + */ + public static File getMainFileByType(File dir) { + File xx = new File(dir.getAbsolutePath() + "/main.py"); + return xx.exists() ? xx : null; + } + + /** + * Filter Files by type + * + * @param dir + * @return + */ + public static File[] getPyFiles(File dir) { + if (dir==null) { + return null; + } + typeFiles = new ArrayList<>(); + addPyFile(dir); + return typeFiles.toArray(new File[0]); + } + + private static void addPyFile(File dir) { + File[] dirFiles = dir.listFiles(); + if (dirFiles!=null) { + for (File file : dirFiles) { + if (file.isDirectory() && !file.getAbsolutePath().contains("/.")) { + addPyFile(file); + } else { + String filename = file.getName(); + if ((filename.endsWith(".py")||filename.endsWith(".ipynb")) && filename.charAt(0)!='.') + typeFiles.add(file); + } + } + } + } + + public static void copyFile(File file, String outputPath) { + int BUFFER_SIZE = 4069; + try { + InputStream inputStream = new FileInputStream(file); + OutputStream outputStream = new FileOutputStream(outputPath); + + byte[] buffer = new byte[BUFFER_SIZE]; + int bytesRead; + + while ((bytesRead = inputStream.read(buffer)) != -1) { + outputStream.write(buffer, 0, bytesRead); + } + } catch (IOException ex) { + ex.printStackTrace(); + } + } + + public static void moveFile(File file, String outputPath) { + if (file.isDirectory()) { + for (File file1 : file.listFiles()) { + moveFile(file1, outputPath); + } + file.delete(); + } else { + copyFile(file, outputPath + "/" + file.getName()); + file.delete(); + } + } + + /** + * @param file root file + * @return all sub-file except dir file and hided file(start with '.') + */ + public static List filterDir(File file) { + List files = new ArrayList<>(); + File[] subFile = file.listFiles(); + if (subFile != null) { + for (File file1 : subFile) { + if (!file1.isDirectory()) { + files.add(file1); + } else if (!file1.getName().startsWith(".")) { + files.addAll(filterDir(file1)); + } + } + } + return files; + } + + + + public static List filterExt(File dir, String[] exts, int size) { + List filtered = new ArrayList<>(); + List files = filterDir(dir); + for (File file : files) { + if (file.getName().startsWith(".")) { + continue; + } + String ext = ""; + if (file.getName().lastIndexOf(".") > 0) { + ext = file.getName().substring(file.getName().lastIndexOf(".") + 1); + } + for (String s : exts) { + if (s.equals(ext)) { + filtered.add(file); + size += 1; + } + } + } + return filtered; + } + + public static List filterExt(File dir, String[] exts) { + List filtered = new ArrayList<>(); + List files = filterDir(dir); + for (File file : files) { + if (file.getName().startsWith(".")) { + continue; + } + String ext = ""; + if (file.getName().lastIndexOf(".") > 0) { + ext = file.getName().substring(file.getName().lastIndexOf(".") + 1); + } + for (String s : exts) { + if (s.equals(ext)) { + filtered.add(file); + } + } + } + return filtered; + } + + public static File findFile(File dir, String findName) { + File result = null; + if (dir.isDirectory()) { + for (File file : dir.listFiles()) { + if (file.isDirectory()) { + File ret = findFile(file, findName); + if (ret != null) { + result = ret; + } + } else { + if (file.getName().equals(findName)) { + result = file; + } + } + } + return result; + } else { + return dir; + } + } +} diff --git a/src/main/java/com/quseit/util/FileUtils.java b/src/main/java/com/quseit/util/FileUtils.java deleted file mode 100644 index 0fc9a2badb31c92e80ac6a1b5c72d5bf40970a80..0000000000000000000000000000000000000000 --- a/src/main/java/com/quseit/util/FileUtils.java +++ /dev/null @@ -1,262 +0,0 @@ -/* - * Copyright (C) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ - -package com.quseit.util; - -import android.content.Context; -import android.content.res.AssetManager; -import android.os.Build; -import android.os.Environment; -import android.support.annotation.RequiresApi; -import android.system.ErrnoException; -import android.system.Os; - -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.InputStreamReader; -import java.io.OutputStream; -import java.lang.reflect.Method; -import java.nio.channels.FileChannel; -import java.nio.file.Files; -import java.nio.file.attribute.PosixFilePermission; -import java.util.HashSet; -import java.util.Set; - -/** - * Utility functions for handling files. - * - * @author Damon Kohler (damonkohler@gmail.com) - */ -public class FileUtils { - private static final String TAG = "FileUtils"; - - private FileUtils() {} - - public static String getScriptsRootPath(Context context){ - return getQyPath() + "/sl4a/scripts/"; - } - - public static String getCloudMapCachePath(Context context){ - return getAbsolutePath(context) + "/lib/.cloud_cache"; - } - - public static String getPyCachePath(Context context){ - return getAbsolutePath(context) + ".qpyc"; - } - - public static String getAbsoluteLogPath(Context context){ - return getAbsolutePath(context) + "/log/last.log"; - } - - public static String getLibDownloadTempPath(Context context){ - return getAbsolutePath(context) + "/cache"; - } - - public static String getAbsolutePath(Context context){ -// return context.getExternalFilesDir(null).getPath() + "/qpython"; - //return Environment.getExternalStorageDirectory().getPath() + "/qpython"; - return context.getExternalFilesDir("").getPath(); - } - - public static File getPath(Context context){ - return context.getExternalFilesDir(null); - } - - public static String getQyPath(){ -// return context.getExternalFilesDir(null).getAbsolutePath(); - return Environment.getExternalStorageDirectory().getPath(); - } - - static public boolean externalStorageMounted() { - String state = Environment.getExternalStorageState(); - return Environment.MEDIA_MOUNTED.equals(state) - || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state); - } - - public static int chmod(File path, int mode) throws Exception { - Class fileUtils = Class.forName("android.os.FileUtils"); - Method setPermissions = fileUtils.getMethod("setPermissions", String.class, int.class, int.class, int.class); - Object invokePer = setPermissions.invoke(null, path.getAbsolutePath(), mode, -1, -1); - if (invokePer instanceof Integer){ - return (Integer) invokePer; - }else { - return 0; - } -// return (Integer) setPermissions.invoke(null, path.getAbsolutePath(), mode, -1, -1); - } - - @RequiresApi(api = Build.VERSION_CODES.O) - public static void setPermission(File file) throws IOException { - Set perms = new HashSet<>(); - perms.add(PosixFilePermission.OWNER_READ); - perms.add(PosixFilePermission.OWNER_WRITE); - perms.add(PosixFilePermission.OWNER_EXECUTE); - - perms.add(PosixFilePermission.OTHERS_READ); - perms.add(PosixFilePermission.OTHERS_WRITE); - perms.add(PosixFilePermission.OTHERS_EXECUTE); - - perms.add(PosixFilePermission.GROUP_READ); - perms.add(PosixFilePermission.GROUP_WRITE); - perms.add(PosixFilePermission.GROUP_EXECUTE); - - Files.setPosixFilePermissions(file.toPath(), perms); - } - - public static boolean recursiveChmod(File root, int mode) throws Exception { - boolean success = chmod(root, mode) == 0; - File[] files = root.listFiles(); - if (files != null){ - for (File path : files) { - if (path.isDirectory()) { - success = recursiveChmod(path, mode); - } - success &= (chmod(path, mode) == 0); - } - } - return success; - } - - public static boolean delete(File path) { - boolean result = true; - if (path.exists()) { - if (path.isDirectory()) { - File[] files = path.listFiles(); - if (files != null){ - for (File child : files) { - result &= delete(child); - } - } - // Delete empty directory. - result &= path.delete(); - } - if (path.isFile()) { - result &= path.delete(); - } - if (!result) { - Log.e(TAG, "Delete failed;"); - } - return result; - } else { - Log.e(TAG, "File does not exist."); - return false; - } - } - - public static File copyFromStream(String name, InputStream input) { - if (name == null || name.length() == 0) { - Log.e(TAG, "No script name specified."); - return null; - } - File file = new File(name); - if (!makeDirectories(file.getParentFile(), 0755)) { - return null; - } - try { - OutputStream output = new FileOutputStream(file); - IoUtils.copy(input, output); - } catch (Exception e) { - Log.e(TAG, e); - return null; - } - return file; - } - - public static boolean makeDirectories(File directory, int mode) { - File parent = directory; - while (parent.getParentFile() != null && !parent.exists()) { - parent = parent.getParentFile(); - } - if (!directory.exists()) { - Log.d(TAG, "Creating directory: " + directory.getName()); - if (!directory.mkdirs()) { - Log.e(TAG, "Failed to create directory."); - return false; - } - } - try { - recursiveChmod(parent, mode); - } catch (Exception e) { - Log.e(TAG, e); - return false; - } - return true; - } - -// public static File getExternalDownload() { -// try { -// Class c = Class.forName("android.os.Environment"); -// Method m = c.getDeclaredMethod("getExternalStoragePublicDirectory", String.class); -// String download = c.getDeclaredField("DIRECTORY_DOWNLOADS").get(null).toString(); -// return (File) m.invoke(null, download); -// } catch (Exception e) { -//// return new File(Environment.getExternalStorageDirectory(), "Download"); -// return new File(Environment.getExternalStorageDirectory(), "Download"); -// } -// } - - public static boolean rename(File file, String name) { - return file.renameTo(new File(file.getParent(), name)); - } - - public static String readToString(File file) throws IOException { - if (file == null || !file.exists()) { - return null; - } - FileReader reader = new FileReader(file); - StringBuilder out = new StringBuilder(); - char[] buffer = new char[1024 * 4]; - int numRead = 0; - while ((numRead = reader.read(buffer)) > -1) { - out.append(String.valueOf(buffer, 0, numRead)); - } - reader.close(); - return out.toString(); - } - - public static String readFromAssetsFile(Context context, String name) throws IOException { - AssetManager am = context.getAssets(); - BufferedReader reader = new BufferedReader(new InputStreamReader(am.open(name))); - String line; - StringBuilder builder = new StringBuilder(); - while ((line = reader.readLine()) != null) { - builder.append(line); - } - reader.close(); - return builder.toString(); - } - - public static void lnOrcopy(File src, File dst, int sdk) throws IOException, ErrnoException { - - if (sdk>=21) { - Os.symlink(src.getAbsolutePath(), dst.getAbsolutePath()); - } else { - FileInputStream inStream = new FileInputStream(src); - FileOutputStream outStream = new FileOutputStream(dst); - FileChannel inChannel = inStream.getChannel(); - FileChannel outChannel = outStream.getChannel(); - inChannel.transferTo(0, inChannel.size(), outChannel); - inStream.close(); - outStream.close(); - } - } - -} diff --git a/src/main/java/com/quseit/util/IoUtils.java b/src/main/java/com/quseit/util/IoUtils.java deleted file mode 100644 index af47d86a36a2f681006e4a6085e4fe04e8410b91..0000000000000000000000000000000000000000 --- a/src/main/java/com/quseit/util/IoUtils.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ - -package com.quseit.util; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -public class IoUtils { - private static final int BUFFER_SIZE = 1024 * 8; - - private IoUtils() { - // Utility class. - } - - public static int copy(InputStream input, OutputStream output) throws Exception, IOException { - byte[] buffer = new byte[BUFFER_SIZE]; - - BufferedInputStream in = new BufferedInputStream(input, BUFFER_SIZE); - BufferedOutputStream out = new BufferedOutputStream(output, BUFFER_SIZE); - int count = 0, n = 0; - try { - while ((n = in.read(buffer, 0, BUFFER_SIZE)) != -1) { - out.write(buffer, 0, n); - count += n; - } - out.flush(); - } finally { - try { - out.close(); - } catch (IOException e) { - Log.e(e.getMessage(), e); - } - try { - in.close(); - } catch (IOException e) { - Log.e(e.getMessage(), e); - } - } - return count; - } - -} diff --git a/src/main/java/com/quseit/util/Utils.java b/src/main/java/com/quseit/util/Utils.java index c731bfcf35e6eda41f35d61362f6c87f1efe2ba1..376de26cb9836242cfbf9a7d1af468eefb4b297a 100644 --- a/src/main/java/com/quseit/util/Utils.java +++ b/src/main/java/com/quseit/util/Utils.java @@ -25,6 +25,8 @@ import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; +import util.FileUtil; + public class Utils { private static final String TAG = "Utils"; @@ -120,14 +122,14 @@ public class Utils { } else { if(zipEntry.isDirectory()){ file.mkdirs(); - FileUtils.chmod(file, 0755); + FileUtil.chmod(file, 0755); }else{ // create parent file folder if not exists yet if(!file.getParentFile().exists()) { file.getParentFile().mkdirs(); - FileUtils.chmod(file.getParentFile(), 0755); + FileUtil.chmod(file.getParentFile(), 0755); } byte buffer[] = new byte[BUFFER_SIZE]; @@ -144,7 +146,7 @@ public class Utils { } if(file.getName().endsWith(".so")) { - FileUtils.chmod(file, 0755); + FileUtil.chmod(file, 0755); } Log.d(TAG,"Unzip extracted " + dest + zipEntryName); @@ -192,15 +194,15 @@ public class Utils { try { if(Environment.getExternalStorageState().equalsIgnoreCase("mounted")) { // File file = new File(Environment.getExternalStorageDirectory(), path); - File file = new File(FileUtils.getQyPath(), path); + File file = new File(FileUtil.getQyPath(), path); if (!file.exists()) { try { file.mkdirs(); // Log.d(TAG, "createDirectoryOnExternalStorage created " + Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +path); - Log.d(TAG, "createDirectoryOnExternalStorage created " + FileUtils.getQyPath() + "/" +path); + //Log.d(TAG, "createDirectoryOnExternalStorage created " + FileUtil.getQyPath() + "/" +path); } catch (Exception e) { - Log.e(TAG,"createDirectoryOnExternalStorage error: ", e); + //Log.e(TAG,"createDirectoryOnExternalStorage error: ", e); } } } @@ -251,7 +253,7 @@ public class Utils { if (hasSdcard()) { // SD卡路径 // filePath = Environment.getExternalStorageDirectory() - filePath = FileUtils.getQyPath() + filePath = FileUtil.getQyPath() + File.separator + dirName; } else { filePath = context.getCacheDir().getPath() + File.separator