Java tutorial
/* Copyright 2012-2013, Polyvi Inc. (http://polyvi.github.io/openxface) This program is distributed under the terms of the GNU General Public License. This file is part of xFace. xFace 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 3 of the License, or (at your option) any later version. xFace 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 xFace. If not, see <http://www.gnu.org/licenses/>. */ package com.polyvi.xface.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; 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.io.OutputStreamWriter; import java.io.RandomAccessFile; import java.nio.channels.FileChannel; import java.util.Date; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.content.res.Resources.NotFoundException; import android.os.Environment; import android.webkit.MimeTypeMap; import com.polyvi.xface.core.XConfiguration; public class XFileUtils { private final static String CLASS_NAME = XFileUtils.class.getSimpleName(); // TODO:??????? public final static String ALL_PERMISSION = "777"; // ???? public final static String EXECUTABLE_BY_OTHER = "701"; // ??? public final static String READABLE_BY_OTHER = "704"; // ??? public final static String READABLE_AND_EXECUTEBLE_BY_OTHER = "705";// ??:?? private static final int OCTAL_RADIX = 8; // private static String NO_MEDIA_FILE_NAME = ".nomedia"; private static final String FILE_DIRECTORY = "raw"; /** * * * @param filePath * ? * @param data * ?? * @return ?? */ public static long write(String fileName, String data, int position) throws FileNotFoundException, IOException { boolean append = false; if (position > 0) { truncateFile(fileName, position); append = true; } byte[] rawData = data.getBytes(); ByteArrayInputStream in = new ByteArrayInputStream(rawData); FileOutputStream out = new FileOutputStream(fileName, append); byte buff[] = new byte[rawData.length]; in.read(buff, 0, buff.length); out.write(buff, 0, rawData.length); out.flush(); out.close(); return data.length(); } /** * ? * * @param filePath * ? * @param size * size? * @return */ public static long truncateFile(String fileName, long size) throws FileNotFoundException, IOException { RandomAccessFile raf = new RandomAccessFile(fileName, "rw"); if (raf.length() >= size) { FileChannel channel = raf.getChannel(); channel.truncate(size); return size; } return raf.length(); } /** * ? * * @param fileName * * @return */ public static String getMimeType(String filename) { MimeTypeMap map = MimeTypeMap.getSingleton(); return map.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(filename)); } /** * * * @param path * ? * @return ?true,false */ public static Boolean createFile(String path) { File file = new File(path); File parantFile = file.getParentFile(); if (null != parantFile && !parantFile.exists() && !parantFile.mkdirs()) { return false; } try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); return false; } return true; } /** * ?sdcard * * @return sdcard??sdcard?null */ public static String getSdcardPath() { String path = null; if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { path = Environment.getExternalStorageDirectory().getAbsolutePath(); } else { path = XExternalStorageScanner.getExternalStoragePath(); } if (null == path) { XLog.w(CLASS_NAME, "No External Storage"); return null; } File filePath = null; try { filePath = new File(path).getCanonicalFile(); } catch (IOException e) { XLog.e(CLASS_NAME, e.getMessage()); e.printStackTrace(); return null; } return filePath.getAbsolutePath(); } /** * JSON * * @param appWorkSpace * ? * @param file * ? * @return JSON * @throws JSONException */ public static JSONObject getEntry(String appWorkspace, File file) throws JSONException { JSONObject entry = new JSONObject(); entry.put("isFile", file.isFile()); entry.put("isDirectory", file.isDirectory()); String fileName = null; String fullPath = null; String absolutePath = file.getAbsolutePath(); if (absolutePath.equals(appWorkspace)) { fileName = File.separator; fullPath = File.separator; } else if (XFileUtils.isFileAncestorOf(appWorkspace, absolutePath)) { fullPath = file.getAbsolutePath().substring(appWorkspace.length()); fileName = file.getName(); } entry.put("name", fileName); entry.put("fullPath", fullPath); entry.put("start", 0); entry.put("end", file.length()); return entry; } /** * ?? * * @param permission * ?? * @param path * */ public static void setPermission(String permission, String path) { XNativeBridge.chmod(path, Integer.parseInt(permission, OCTAL_RADIX)); } /** * ??dir * * @param permission * ?? * @param filePath * ?? * @param dir * ????(?filePath"/"??) */ public static void setPermissionUntilDir(String permission, String filePath, String dir) { String dirPath = new File(dir).getAbsolutePath(); if (null == filePath || !filePath.startsWith(dirPath)) { return; } File fileObj = new File(filePath); while (!dirPath.equals(fileObj.getAbsolutePath())) { String path = fileObj.getAbsolutePath(); // ?? setPermission(permission, path); fileObj = new File(fileObj.getParent()); } } /** * ? * * @param filePath * * @return true,false:?. */ public static boolean checkFileExist(String filePath) { if (XStringUtils.isEmptyString(filePath)) { XLog.e(CLASS_NAME, "filePath is empty"); return false; } if (!new File(filePath).exists()) { XLog.e(CLASS_NAME, filePath + " not exist"); return false; } return true; } /** * * * @param parent * parent? * @return null ??? */ public static String createTempDir(String parent) { if (!parent.endsWith("/")) { parent += "/"; } String dirPath = parent + String.valueOf(new Date().getSeconds()) + XUtils.generateRandomId() + "tmp"; File tmpFile = new File(dirPath); return tmpFile.mkdir() ? tmpFile.getAbsolutePath() : null; } /** * ? * * @param src * ?? * @param des * ? * @throws IOException */ public static void copy(File srcLocation, File desLocation) throws IOException { if (srcLocation.isDirectory()) { if (!desLocation.exists() && !desLocation.mkdirs()) { throw new IOException("can't create dir " + desLocation.getAbsolutePath()); } String[] children = srcLocation.list(); for (int i = 0; i < children.length; i++) { copy(new File(srcLocation, children[i]), new File(desLocation, children[i])); } } else { File direcory = desLocation.getParentFile(); if (direcory != null && !direcory.exists() && !direcory.mkdirs()) { throw new IOException("can't create dir " + direcory.getAbsolutePath()); } InputStream in = new FileInputStream(srcLocation); OutputStream out = new FileOutputStream(desLocation); byte[] buf = new byte[XConstant.BUFFER_LEN]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); } } /** * ?? * * @param srcDir * ??? * @param handler * ? */ public static void walkDirectory(String srcDir, XFileVisitor visitor) { walkDirectory(new File(srcDir), visitor); } /** * ?? * * @param srcDir * ??? * @param visitor * ? */ public static void walkDirectory(File srcDir, XFileVisitor visitor) { if (!srcDir.exists() || !srcDir.isDirectory() || !visitor.isContinueTraverse()) { return; } File files[] = srcDir.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { visitor.visit(files[i].getAbsolutePath()); } else { walkDirectory(files[i], visitor); } } } /** * ?urlMIMEType * * @paramm url url? * @return MIMEType */ public static String getMIMEType(String url) { int dotIndex = url.lastIndexOf("."); /* ???? */ return dotIndex < 0 ? "*/*" : MimeTypeMap.getSingleton() .getMimeTypeFromExtension(url.substring(dotIndex + 1, url.length()).toLowerCase()); } /** * * * @param path * / */ public static boolean deleteFileRecursively(String path) { File destFile = new File(path); if (!destFile.exists()) { return true; } if (destFile.isFile()) { destFile.delete(); return true; } String[] childNames = destFile.list(); for (String child : childNames) { if (!deleteFileRecursively(new File(path, child).getAbsolutePath())) { return false; } } return destFile.delete(); } /** * <br> * ? * * @param filePath * ? * @param is * ?? */ public static void createFileByData(String filePath, InputStream is) { try { File destFile = new File(filePath); File parentFile = destFile.getParentFile(); if (!parentFile.exists()) { parentFile.mkdirs(); } FileOutputStream fos = new FileOutputStream(destFile); byte[] buffer = new byte[XConstant.BUFFER_LEN]; int len = 0; while (-1 != (len = is.read(buffer))) { fos.write(buffer, 0, len); } fos.close(); } catch (IOException e) { XLog.e(CLASS_NAME, e.getMessage()); e.printStackTrace(); } } /** * zip * * @param targetPath * * @param zipFilePath * zip * * @return ?? */ public static boolean unzipFile(String targetPath, String zipFilePath) { try { XZipper zipper = new XZipper(); zipper.unzipFile(targetPath, zipFilePath); return true; } catch (FileNotFoundException e) { XLog.e(CLASS_NAME, "The zip file: " + zipFilePath + "does not exist!"); e.printStackTrace(); return false; } catch (IOException e) { XLog.e(CLASS_NAME, "Unzip file: " + zipFilePath + " failed!"); e.printStackTrace(); return false; } } /** * assets??zip * * @param targetPath * * @param context * @param assetFileName * ?assets??? */ public static boolean unzipFileFromAsset(String targetPath, Context context, String assetFileName) { try { return new XZipper().unzipFileFromAsset(targetPath, context, assetFileName); } catch (IOException e) { XLog.e(CLASS_NAME, "Unzip file failed: Can't find assets file: " + assetFileName); return false; } } /** * ?? * * @param filePath * ? * @return ?? */ public static String readFileContent(String filePath) { if (null == filePath) { return null; } try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); FileInputStream fis = new FileInputStream(filePath); byte[] buffer = new byte[XConstant.BUFFER_LEN]; int len = 0; while ((len = fis.read(buffer)) != -1) { bos.write(buffer, 0, len); } String content = bos.toString(); bos.close(); fis.close(); return content; } catch (FileNotFoundException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } } /** * ?? childPathparentPath?childPathparentPath * * @param parentPath * * @param childPath * * @return true:parentPathfalse:?parentPath */ public static boolean isFileAncestorOf(String parentPath, String childPath) { if (!parentPath.endsWith(File.separator)) { parentPath += File.separator; } if (!childPath.endsWith(File.separator)) { childPath += File.separator; } return childPath.startsWith(parentPath); } /** * ?xface.js * * @param context * android?? * @param targetDir * ?xface.js? */ public static void copyEmbeddedJsFile(Context context, String targetDir) { try { int id = context.getResources().getIdentifier( XConstant.XFACE_JS_FILE_NAME.substring(0, XConstant.XFACE_JS_FILE_NAME.length() - 3), FILE_DIRECTORY, context.getPackageName()); InputStream is = context.getResources().openRawResource(id); File jsFile = new File(targetDir, XConstant.XFACE_JS_FILE_NAME); createFileByData(jsFile.getAbsolutePath(), is); is.close(); } catch (IOException e) { e.printStackTrace(); } catch (NotFoundException e) { XLog.e(CLASS_NAME, "Can't find resource file xface.js in res/raw folder!"); e.printStackTrace(); } } /** * ?xdebug.js * * @param context * android?? * @param targetDir * ?xdebug.js? */ public static void copyEmbeddedDebugJsFile(Context context, String targetDir) { // todo:? try { int id = context.getResources().getIdentifier( XConstant.DEBUG_JS_FILE_NAME.substring(0, XConstant.DEBUG_JS_FILE_NAME.length() - 3), FILE_DIRECTORY, context.getPackageName()); InputStream is = context.getResources().openRawResource(id); File jsFile = new File(targetDir, XConstant.DEBUG_JS_FILE_NAME); createFileByData(jsFile.getAbsolutePath(), is); is.close(); } catch (IOException e) { e.printStackTrace(); } catch (NotFoundException e) { XLog.e(CLASS_NAME, "Can't find resource file xdebug.js in res/raw folder!"); e.printStackTrace(); } } /** * xFacewordDir.nomedia */ public static void createNoMediaFileInWorkDir() { File file = new File(XConfiguration.getInstance().getWorkDirectory(), NO_MEDIA_FILE_NAME); try { if (!file.exists()) { file.createNewFile(); } } catch (IOException e) { XLog.e(CLASS_NAME, "create .nomedia in workDir failed."); } } /** * ? * * @param filePath * ? * @param fileContent * ? * @return ?truefalse */ public static Boolean writeFileByByte(String filePath, byte[] fileContent) { try { if (null == filePath || null == fileContent) { return false; } FileOutputStream fileOutputStream = new FileOutputStream(filePath); fileOutputStream.write(fileContent); fileOutputStream.flush(); fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); XLog.d(CLASS_NAME, e.getMessage()); return false; } return true; } /** * ? * * @param filePath * ? * @param fileContent * ? * @return ?truefalse */ public static boolean writeFileByString(String filePath, String fileContent) { if (null == filePath || null == fileContent) { return false; } try { OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(filePath)); outputStreamWriter.write(fileContent, 0, fileContent.length()); outputStreamWriter.flush(); outputStreamWriter.close(); } catch (IOException e) { e.printStackTrace(); XLog.d(CLASS_NAME, e.getMessage()); return false; } return true; } /** * ?? * * @param filePath * ? * @return ???null */ public static byte[] readBytesFromFile(String filePath) { if (null == filePath) { return null; } InputStream is = null; try { is = new FileInputStream(filePath); return XUtils.readBytesFromInputStream(is); } catch (Exception e) { XLog.d(CLASS_NAME, "readFileByByte:" + e.getMessage()); e.printStackTrace(); return null; } } /** * ? * * @param filePath * [in] * * @return * */ public static boolean fileExists(Context context, String filePath) { if (null == filePath) { return false; } String absPath = null; if (filePath.startsWith(XConstant.ASSERT_PROTACAL)) { absPath = filePath.substring(XConstant.ASSERT_PROTACAL.length()); try { InputStream is = context.getAssets().open(absPath); if (is != null) { return true; } } catch (IOException e) { return false; } } else if (filePath.startsWith(XConstant.FILE_SCHEME)) { File file = new File(filePath.substring(XConstant.FILE_SCHEME.length())); if (file.exists()) { return true; } } return false; } }