/** * Create and returns the Bitmap image from local storage optimized by size * * @param imageID - filename of the image * @param reqSize - maximum side of image returns default image (DEFAULT_IMAGE_NAME) if image * can't be loaded used in ArticleViewAdapter.getView() */ public static Bitmap getBitmapFromStorage(Context context, String imageID, int reqSize) { Log.d(TAG, ".getBitmapFromFilePath(), image=" + imageID + ", size=" + reqSize); Bitmap result = null; // construct full file name String fileName = imageID + JPEG_SUFFIX; File imageFile = new File(context.getExternalFilesDir(Utils.TYPE_PICTURE), fileName); // if image file exists trying to load, optimize and decode if (imageFile.exists()) { // First decode with inJustDecodeBounds=true to check dimensions BitmapFactory.Options bmOptions = new BitmapFactory.Options(); bmOptions.inJustDecodeBounds = true; BitmapFactory.decodeFile(imageFile.getAbsolutePath(), bmOptions); // Calculate inSampleSize bmOptions.inSampleSize = calculateImageInSampleSize(bmOptions, reqSize, reqSize); // Decode bitmap with inSampleSize set from file with given options bmOptions.inJustDecodeBounds = false; bmOptions.inPurgeable = true; result = BitmapFactory.decodeFile(imageFile.getAbsolutePath(), bmOptions); } // if can't be loaded and decoded, load default image from local storage instead if (result == null) { Log.d(TAG, ".getBitmapFromFilePath(), cann't decode image:" + imageFile.getAbsolutePath()); File file = new File(context.getExternalFilesDir(TYPE_PICTURE), DEFAULT_IMAGE_NAME); result = BitmapFactory.decodeFile(file.getAbsolutePath()); } return result; }
/** Load html file from local storage Used in ArticleFragment */ public static String getUrlFileFromStorage(Context context, String articleID) { Log.d(TAG, ".getUrlFileFromStorage(), articleID=" + articleID); // check if the file exists File html = new File(context.getExternalFilesDir(Utils.TYPE_DOCUMENT), articleID + HTML_SUFFIX); // if file doesn't exists, return path к тексту по умолчанию if (!html.exists()) html = new File(context.getExternalFilesDir(Utils.TYPE_DOCUMENT), DEFAULT_HTML_NAME); return (HTML_PREFIX + html.getAbsolutePath()); }
private List<StorageMount> getSecondayExternals(Context context) { List<StorageMount> mounts = new ArrayList<StorageMount>(); String primaryPath = context.getExternalFilesDir(null).getParent(); int i = 0; for (File f : SystemUtils.getExternalFilesDirs(context)) { if (!f.getAbsolutePath().startsWith(primaryPath) && SystemUtils.isSecondaryExternalStorageMounted(f)) { String label = context.getString(R.string.sdcard_storage) + " " + (++i); String description = UIUtils.getBytesInHuman(SystemUtils.getAvailableStorageSize(f)) + " " + context.getString(R.string.available); String path = f.getAbsolutePath(); StorageMount mount = new StorageMount(label, description, path, false); mounts.add(mount); } } return mounts; }
private void openIfRequired() throws IOException { String state = Environment.getExternalStorageState(); if (mSerializer == null) { String fileName = mReportFile; if (mMultiFile) { fileName = fileName.replace("$(suite)", "test"); } if (mReportDir == null) { if (Environment.MEDIA_MOUNTED.equals(state) && !Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { File f = mContext.getExternalFilesDir("testng"); mOutputStream = new FileOutputStream(new File(f, fileName)); } else { mOutputStream = mTargetContext.openFileOutput(fileName, 0); } } else { mOutputStream = new FileOutputStream(new File(mReportDir, fileName)); } mSerializer = Xml.newSerializer(); mSerializer.setOutput(mOutputStream, ENCODING_UTF_8); mSerializer.startDocument(ENCODING_UTF_8, true); if (!mMultiFile) { mSerializer.startTag("", TAG_SUITES); } } }
public static Object readObjectFile(Context context, String filename, Boolean external) { Object content = new Object(); try { File file; FileInputStream fin; if (external) { file = new File(context.getExternalFilesDir(null), filename); fin = new FileInputStream(file); } else { file = new File(filename); fin = context.openFileInput(filename); } ObjectInputStream ois = new ObjectInputStream(fin); try { content = (Object) ois.readObject(); } catch (ClassNotFoundException e) { Log.e("READ ERROR", "INVALID JAVA OBJECT FILE"); } ois.close(); fin.close(); } catch (FileNotFoundException e) { Log.e("READ ERROR", "FILE NOT FOUND " + filename); return null; } catch (IOException e) { Log.e("READ ERROR", "I/O ERROR"); } return content; }
public static String readStringFile(Context context, String filename, Boolean external) { String content = ""; try { File file; FileInputStream fin; if (external) { file = new File(context.getExternalFilesDir(null), filename); fin = new FileInputStream(file); } else { file = new File(filename); fin = context.openFileInput(filename); } BufferedInputStream bin = new BufferedInputStream(fin); byte[] contentBytes = new byte[1024]; int bytesRead = 0; StringBuffer contentBuffer = new StringBuffer(); while ((bytesRead = bin.read(contentBytes)) != -1) { content = new String(contentBytes, 0, bytesRead); contentBuffer.append(content); } content = contentBuffer.toString(); fin.close(); } catch (FileNotFoundException e) { Log.e("READ ERROR", "FILE NOT FOUND " + filename); } catch (IOException e) { Log.e("READ ERROR", "I/O ERROR"); } return content; }
public boolean DownloadFile(String fileURL, String filename, Context con) { DeleteFileIfExist(filename, con); try { File file = new File(con.getExternalFilesDir(null), filename); FileOutputStream f = new FileOutputStream(file); URL u = new URL(fileURL); HttpURLConnection c = (HttpURLConnection) u.openConnection(); c.setRequestMethod("GET"); c.setAllowUserInteraction(false); c.setDoInput(true); // c.setDoOutput(true); c.setReadTimeout(10000); c.connect(); InputStream in = c.getInputStream(); byte[] buffer = new byte[1024]; int len1 = 0; while ((len1 = in.read(buffer)) > 0) { f.write(buffer, 0, len1); } f.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
/** * Download files from url by the stream used in DownloadDataStreamService silently return if * something goes wrong */ public static String downloadUsingStream( Context context, String urlStr, String fileType, String fileId) { Log.d( TAG, "downloadUsingStream()" + "; id=" + fileId + ", type=" + fileType + ", url=" + urlStr); String result = ""; try { // Note that if external storage is not currently mounted this will silently fail. File storageDir = context.getExternalFilesDir(fileType); // define file name with extention out from fileType String fileName = fileId + (fileType == Utils.TYPE_PICTURE ? ".jpg" : ".html"); File file = new File(storageDir, fileName); URL url = new URL(urlStr); BufferedInputStream bis = new BufferedInputStream(url.openStream()); FileOutputStream fis = new FileOutputStream(file); byte[] buffer = new byte[Utils.BUFFER_SIZE]; int count = 0; while ((count = bis.read(buffer, 0, Utils.BUFFER_SIZE)) != -1) fis.write(buffer, 0, count); fis.close(); bis.close(); result = file.getAbsolutePath(); } catch (IOException ex) { Log.e(TAG, ".onHandleIntent(); Error downloadUsingStream(), url=" + urlStr, ex); } // return path to downloaded file return result; }
/** * 下载一个文件 * * @param dirType * @param subPath * @param url * @param isOverite 复盖原有文件,删除原来的链接 * @return */ public long downLoadFile( String dirType, String subPath, final String url, boolean isExternal, boolean isOverite) { if (isOverite) { // 如果存在就先删除 final File dirtype = context.getExternalFilesDir(dirType); Uri.Builder builder = Uri.fromFile(dirtype).buildUpon(); builder = builder.appendEncodedPath(subPath); File file = new File(builder.build().getPath()); if (file.exists()) { file.delete(); } // 判断是否在下载列表中,有在下载列表中就先删除 List<DownloadStatus> downloadStatusList = getAllDownloadList(); for (DownloadStatus downloadStatus : downloadStatusList) { if (downloadStatus.getUrl().equals(url)) { deleteDownload(downloadStatus.getDownloadId()); } } return downLoadFile(dirType, subPath, url, isExternal); } else { return downLoadFile(dirType, subPath, url, isExternal); } }
public boolean loadTexture(String path) { Bitmap bitmap = null; try { String str = path; if (!path.startsWith("/")) { str = "/" + path; } File file = new File(context.getExternalFilesDir(null), str); if (file.canRead()) { bitmap = BitmapFactory.decodeStream(new FileInputStream(file)); } else { bitmap = BitmapFactory.decodeStream(context.getResources().getAssets().open(path)); } // Matrix matrix = new Matrix(); // // resize the bit map // matrix.postScale(-1F, 1F); // // // recreate the new Bitmap and set it back // bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), // bitmap.getHeight(), matrix, true); } catch (Exception e) { Log.w("NDKHelper", "Coundn't load a file:" + path); return false; } if (bitmap != null) { GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); } return true; }
public static File GetDefaultStorageFolder(Context context) { File storageFolder = context.getExternalFilesDir(null); if (storageFolder == null) { storageFolder = context.getFilesDir(); } return storageFolder; }
/** * 获得应用的根目录 <br> * <li>如果DEBUG==true,返回的是ExternalStorage路径方便调试 /storage/emulated/0/Android/data/<App Name>/files * <li>如果DEBUG==false,返回的时InternalStorage /data/data/<App Name>/files * * @param context * @return */ @SuppressWarnings("unused") public static String getRootPath(Context context) { if (StorageUtils.isExternalStorageWritable() && DEBUG) { return context.getExternalFilesDir(null).getAbsolutePath(); } return context.getFilesDir().getAbsolutePath(); }
public static Uri exportJekyllPages(Context context) { File exportDirectory = context.getExternalFilesDir(null); String filename = System.currentTimeMillis() + "_jekyll.zip"; File exportedFile = new File(exportDirectory, filename); try { FileOutputStream out = new FileOutputStream(exportedFile); ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(out)); try { BootstrapSiteExporter.writeScriptDocumentation( context, zos, "embedded_website/docs/all", BootstrapSiteExporter.TEMPLATE_TYPE_JEKYLL); BootstrapSiteExporter.writeScriptDocumentation( context, zos, "embedded_website/docs/scheme", BootstrapSiteExporter.TEMPLATE_TYPE_JEKYLL); BootstrapSiteExporter.writeScriptDocumentation( context, zos, "embedded_website/docs/javascript", BootstrapSiteExporter.TEMPLATE_TYPE_JEKYLL); } finally { zos.close(); } } catch (java.io.IOException e) { e.printStackTrace(); } return Uri.fromFile(exportedFile); }
@SuppressWarnings("nls") public static JSONObject savePictureJson(Context context, Bitmap bitmap) { try { String name = DateUtilities.now() + ".jpg"; JSONObject jsonObject = new JSONObject(); jsonObject.put("name", name); jsonObject.put("type", "image/jpeg"); File dir = context.getExternalFilesDir(PICTURES_DIRECTORY); if (dir != null) { File file = new File(dir + File.separator + DateUtilities.now() + ".jpg"); if (file.exists()) return null; try { FileOutputStream fos = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos); fos.flush(); fos.close(); jsonObject.put("path", file.getAbsolutePath()); } catch (FileNotFoundException e) { // } catch (IOException e) { // } return jsonObject; } else { return null; } } catch (JSONException e) { // } return null; }
/** * @param placemarkNameColumn the column whose value will be exported to the KML placemark names. */ public KMLExport(Context context, String placemarkNameColumn) { super( context, new File( context.getExternalFilesDir(null), KML_FILE_PREFIX + placemarkNameColumn + ".kml")); mPlacemarkNameColumn = placemarkNameColumn; }
public File getPhotoFile(Context context) { File externalFilesDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES); // if externalFilesDir is null, return null if (externalFilesDir == null) return null; // send back a new File with arguments // externalFilesDir and the photoFilename return new File(externalFilesDir, getPhotoFilename()); }
public static void saveAlbum(Context context, Album album) throws IOException { if (!storageReady()) { throw new IOException("Storage is not available"); } File path = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES); File file = new File(path, ALBUM_FILE); saveAlbumToFile(album, file); }
public void getProfilePic(String username, ImageView imgV) { Bitmap bitmap = null; SoftReference<Bitmap> bitmapSoft = profilePicCache.get(username); if (bitmapSoft == null) { String pathName; if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { pathName = context.getExternalFilesDir(null).getAbsolutePath() + "/pgim/" + username; } else pathName = context.getCacheDir().getAbsolutePath() + "/pgim/" + username; if (new File(pathName).exists()) { Log.e(TAG, "Get pic from local"); bitmap = BitmapUtil.getBitmapFromLocal(pathName); profilePicCache.put(username, new SoftReference<Bitmap>(bitmap)); } else { new ProfileImageLoader(imgV, pathName).execute(username); return; } } else { if (bitmapSoft.get() == null) { System.out.println("soft bitmap null"); String pathName; if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { pathName = context.getExternalFilesDir(null).getAbsolutePath() + "/pgim/" + username; } else pathName = context.getCacheDir().getAbsolutePath() + "/pgim/" + username; if (new File(pathName).exists()) { Log.e(TAG, "Get pic from local"); bitmap = BitmapUtil.getBitmapFromLocal(pathName); profilePicCache.put(username, new SoftReference<Bitmap>(bitmap)); } else { new ProfileImageLoader(imgV, pathName).execute(username); return; } } else { Log.e(TAG, "Get pic from softreference"); bitmap = bitmapSoft.get(); } } if (bitmap != null) { imgV.setImageBitmap(bitmap); } }
private boolean DeleteFileIfExist(String fileName, Context con) { File file = new File(con.getExternalFilesDir(null), fileName); if (file != null) { file.delete(); } return true; }
/** * it verifies that there is external storage to save them to. if there is no external storage, * return null. it does not create any files on the filesystem. * * @param crime * @return */ public File getPhotoFile(Crime crime) { File externalFilesDir = mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES); if (externalFilesDir == null) { return null; } return new File(externalFilesDir, crime.getPhotoFilename()); }
private File getDefaultDownloadDirectory(Context context) { VizDatabase db = new VizDatabase(context); String dir = db.getDirectory(toSQLString()); db.close(); if (dir == null) { return context.getExternalFilesDir(null); } return new File(dir); }
public boolean hasExternalStoragePrivateFile(String fileName, Context con) { File file = new File(con.getExternalFilesDir(null), fileName); if (file != null) { return file.exists(); } return false; }
public void createApplicationDirectories() { jsonApplication = JsonApplication.getJsonApplication(); Context context = jsonApplication.getApplicationContext(); applicationDir = context.getExternalFilesDir(null); if (applicationDir != null) { applicationDir.mkdirs(); } logsDir = createApplicationSubDirectory(LOGS_DIR_NAME); configureFileLogger(); }
/** Copy all Assets by Type to the local storage returns boolean Uses by InitialActivity */ public static boolean copyAssets(Context context, String assetType, boolean rewrite) { Log.d(TAG, "copyAssets(), assetType=" + assetType); // Get asset manager and define list of files to copy AssetManager assetManager = context.getAssets(); String[] files = null; try { files = assetManager.list(assetType); } catch (IOException ioe) { // exit if something wrong with assets Log.d(TAG, "copyAssets(),Failed to get asset file list.", ioe); return false; } // copy files if exists for (String fileName : files) { InputStream in = null; OutputStream out = null; File outFile = null; // define full path to outFile (depends of asset_type) if (assetType == TYPE_DATABASE) { // check if database directory exists and create if necessary File dir = new File(context.getDatabasePath(fileName).getParent()); if (!dir.exists()) dir.mkdirs(); // create folders where write files outFile = context.getDatabasePath(fileName); } else { outFile = new File(context.getExternalFilesDir(assetType), fileName); } // copy file from asset if file doesn't exists or it need to be rewrited if (rewrite || (!outFile.exists())) { try { // get input stream from Assets in = new BufferedInputStream(assetManager.open(assetType + "/" + fileName), BUFFER_SIZE); out = new BufferedOutputStream(new FileOutputStream(outFile), BUFFER_SIZE); // copy from in to out copyFile(in, out); } catch (IOException ioe) { Log.e(TAG, "copyAssets(), Failed to copy asset: " + fileName, ioe); } finally { // try to close input stream try { in.close(); } catch (IOException ein) { Log.e(TAG, "copyAssets(), filed to close in, file: " + fileName, ein); } try { out.close(); } catch (IOException eout) { Log.e(TAG, "copyAssets(), filed to close out, file: " + fileName, eout); } } } } return true; }
public static Photo loagPhoto(Context context, String fileName) throws IOException { if (!storageReady()) { throw new IOException("Storage is not available"); } File path = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES); File file = new File(path, fileName); if (!file.exists()) { throw new IOException("Photo does not exist"); } return getPhotoFromFile(file); }
public static void savePhoto(Context context, String fileName, Photo photo) throws IOException { if (!storageReady()) { throw new IOException("Storage is not available"); } File path = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES); File file = new File(path, fileName); if (file.exists()) { file.delete(); } savePhotoToFile(photo, file); }
/** * external: "/storage/emulated/0/Android/data/in.srain.sample/files" internal: * "/data/data/in.srain.sample/files" */ public static String wantFilesPath(Context context, boolean externalStorageFirst) { String path = null; File f = null; if (externalStorageFirst && DiskFileUtils.hasSDCardMounted() && (f = context.getExternalFilesDir("xxx")) != null) { path = f.getAbsolutePath(); } else { path = context.getFilesDir().getAbsolutePath(); } return path; }
/** * Persists the JSON string representation of the Tally object to a file on disk * * @param jsonString * @param context */ public void writeTallyJsonToFile(String jsonString, Context context) { if (isExternalStorageWritable()) { File file = new File(context.getExternalFilesDir(null), mode + TALLY_FILENAME); try { FileUtils.writeStringToFile(file, jsonString); } catch (IOException e) { e.printStackTrace(); } } else { Log.w(LOG_TAG, "External storage is not writable"); } }
@Override protected void tearDown() throws Exception { super.tearDown(); assertTrue(PodDBAdapter.deleteDatabase()); final Context context = getInstrumentation().getTargetContext(); File testDir = context.getExternalFilesDir(TEST_FOLDER); assertNotNull(testDir); for (File f : testDir.listFiles()) { f.delete(); } }
/** * Reads the persisted file from disk and returns is as a String. * * @param context * @return */ public String readTallyToJsonString(Context context) { if (isExternalStorageReadable()) { File file = new File(context.getExternalFilesDir(null), mode + TALLY_FILENAME); try { return FileUtils.readFileToString(file); } catch (IOException e) { e.printStackTrace(); } } else { Log.w(LOG_TAG, "External storage is not readable"); } return null; }