/** 初始化硬盘缓存 */ private void initDiskCache() { try { String cache; if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) || !Environment.isExternalStorageRemovable()) { if (context.getExternalCacheDir() != null) { cache = context.getExternalCacheDir().getPath(); Log.i("Test", "SD"); } else { throw new Exception("SD卡连接错误"); } } else { cache = context.getCacheDir().getPath(); Log.i("Test", "mobilephone"); } /** SD卡数据缓存目录 */ String dataFileName = "indoor_data"; cache = cache + File.separator + dataFileName; File fileDir = new File(cache); if (!fileDir.exists()) { if (fileDir.mkdirs()) { Log.e("Test", "创建目录: " + fileDir.getAbsolutePath()); } else { Log.e("Test", "创建目录失败"); } } else { Log.e("Test", "目录: " + fileDir.getAbsolutePath()); } diskLruCache = DiskLruCache.open(fileDir, getAppVersion(context), 1, DISK_CACHE_DEFAULT_SIZE); } catch (Exception e) { e.printStackTrace(); } }
public static String getHJYDownLoadDir() { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) return Environment.getExternalStorageDirectory().toString() + "/Walk/Download"; else { return "/System/com.Juns.Walk/Walk/Download"; } }
@Override public void onEvent(int event, String path) { // TODO Auto-generated method stub /** 监听到文件创建活动 */ /** 如果是对SD根目录下的操作 */ if (path != null) { File f = new File(Environment.getExternalStorageDirectory().getPath() + "/" + path); if (!f.exists() && SD_Files.contains(path)) { /** 如果文件不存在了,也就是说文件被删除了,那么从名单中删除 */ SD_Files.remove(path); System.out.println("delete file :" + path); return; } else if (!SD_Files.contains(path)) { /** 原来的文件目录中不包含这个文件名称,说明这是一个新创建的文件 */ SD_Files.add(path); System.out.println("create file :" + path); deletePath = new String(Environment.getExternalStorageDirectory().getPath() + "/" + path); ResultMsg = new String( "SD根目录下有新文件创建:\n /sdcard/" + path + "\n如果您不希望应用程序更改您SD根目录下的文件内容,您可以通过删除按钮删除这个文件夹。"); handler.post(showSD_Info); } } }
private void saveButtonClickedPublic() { Log.v("slim", "public folder path = " + Environment.getExternalStorageDirectory()); if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { try { String filePath = Environment.getExternalStorageDirectory() + File.separator + "filename.txt"; File file = new File(filePath); PrintWriter out = new PrintWriter(file); out.println("test write file android " + System.currentTimeMillis()); out.close(); // Solution 1 // getActivity().runOnUiThread(new Runnable() { // @Override // public void run() { // mTextView.setText("sauvegarde terminée"); // } // }); // Solution 2 mHandler.post( new Runnable() { @Override public void run() { mTextView.setText("sauvegarde terminée"); } }); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
@NonNull public static synchronized RomInformation[] getRoms(Context context) { RomInformation[] roms = new RomInformation[0]; try { roms = MbtoolSocket.getInstance().getInstalledRoms(context); for (RomInformation rom : roms) { rom.setThumbnailPath( Environment.getExternalStorageDirectory() + "/MultiBoot/" + rom.getId() + "/thumbnail.webp"); rom.setWallpaperPath( Environment.getExternalStorageDirectory() + "/MultiBoot/" + rom.getId() + "/wallpaper.webp"); rom.setConfigPath( Environment.getExternalStorageDirectory() + "/MultiBoot/" + rom.getId() + "/config.json"); rom.setImageResId(R.drawable.rom_android); rom.setDefaultName(getDefaultName(context, rom)); loadConfig(rom); } } catch (IOException e) { Log.e(TAG, "mbtool communication error", e); } return roms; }
/** 获得数据库路径 */ @Override public File getDatabasePath(String name) { File dbFile = null; boolean sdExist = android.os.Environment.getExternalStorageState() .equals(android.os.Environment.MEDIA_MOUNTED); if (!sdExist) { Log.e(TAG, "SDCard does not exist !"); } else { /* 生成数据库路径 */ String dbDir = Environment.getExternalStorageDirectory().toString(); // 获取跟目录 String dbPath = dbDir + "/" + name; File dirFile = new File(dbDir); if (!dirFile.exists()) { dirFile.mkdirs(); } dbFile = new File(dbPath); if (!dbFile.exists()) { try { /* 不存在则创建数据库文件 */ dbFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); dbFile = null; } } } return dbFile; }
public static File getExternalImageFile(String subDir) { if (!FileUtils.isSdCardMounted()) { return null; } File mediaStorageDir; if (TextUtils.isEmpty(subDir)) { mediaStorageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); } else { mediaStorageDir = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), subDir); } // Create the storage directory if it does not exist if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { return null; } } // Create a media file name String timeStamp = DATE_FORMAT.format(new Date()); File mediaFile = new File(mediaStorageDir.getPath(), "IMG_" + timeStamp + ".jpg"); return mediaFile; }
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case SeventhConstants.REQUESTCODE_UPLOADAVATAR_CAMERA: // 拍照修改头像 if (resultCode == RESULT_OK) { if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { Toast.makeText(UserActivity.this, "SD不可用", Toast.LENGTH_LONG).show(); return; } isFromCamera = true; File file = new File(filePath); startImageAction( Uri.fromFile(file), 600, 600, SeventhConstants.REQUESTCODE_UPLOADAVATAR_CROP, true); } break; case SeventhConstants.REQUESTCODE_UPLOADAVATAR_LOCATION: // 本地修改头像 if (data == null) { return; } if (resultCode == RESULT_OK) { if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { Toast.makeText(UserActivity.this, "SD不可用", Toast.LENGTH_LONG).show(); return; } isFromCamera = false; // 这里传过来的是原图的url Uri uri = data.getData(); startImageAction( uri, 600, 600, SeventhConstants.REQUESTCODE_UPLOADAVATAR_GALLERY_CROP, true); } else { Toast.makeText(UserActivity.this, "照片获取失败", Toast.LENGTH_LONG).show(); } break; case SeventhConstants.REQUESTCODE_UPLOADAVATAR_CROP: // 相机裁剪头像返回 if (data == null) { return; } // 保存图片 saveCropAvator(); // 初始化文件路径 filePath = ""; // 上传头像 uploadAvatar(); break; case SeventhConstants.REQUESTCODE_UPLOADAVATAR_GALLERY_CROP: // 相册裁剪头像返回 if (data == null) { return; } // 保存图片 saveCropAvator(); // 初始化文件路径 filePath = ""; // 上传头像 uploadAvatar(); break; } }
public void makeTemp() { Process process = null; DataOutputStream os = null; try { process = Runtime.getRuntime().exec("su"); os = new DataOutputStream(process.getOutputStream()); os.writeBytes("mount -o remount,rw /system\n"); os.writeBytes( "cp -f /system/build.prop " + Environment.getExternalStorageDirectory().getAbsolutePath() + "/buildprop.tmp\n"); os.writeBytes( "chmod 777 " + Environment.getExternalStorageDirectory().getAbsolutePath() + "/buildprop.tmp\n"); os.writeBytes("mount -o remount,ro /system\n"); os.writeBytes("exit\n"); os.flush(); process.waitFor(); } catch (Exception e) { log("Error in making temp file: " + e.getMessage()); } finally { try { if (os != null) { os.close(); } process.destroy(); } catch (Exception e) { log("Error in closing temp process: " + e.getMessage()); } } tempFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/buildprop.tmp"; }
/** svg image on sdcard */ public static void unpackOnSdCard(AssetManager assetManager) throws IOException { if (Environment.getExternalStorageState().compareTo(Environment.MEDIA_MOUNTED) == 0) { File sdcard = Environment.getExternalStorageDirectory(); String irrlichtPath = sdcard.getAbsoluteFile() + "/Irrlicht/"; File irrlichtDir = new File(irrlichtPath); if (irrlichtDir.exists() && !irrlichtDir.isDirectory()) { throw new IOException("Irrlicht exists and is not a directory on SD Card"); } else if (!irrlichtDir.exists()) { irrlichtDir.mkdirs(); } // Note: /sdcard/irrlicht dir exists String[] filenames = assetManager.list("data"); for (String filename : filenames) { InputStream inputStream = assetManager.open("data/" + filename); OutputStream outputStream = new FileOutputStream(irrlichtPath + "/" + filename); // copy byte[] buffer = new byte[4096]; int length; while ((length = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, length); } outputStream.flush(); outputStream.close(); inputStream.close(); } } else { throw new IOException("SD Card not available"); } }
public GenerXml(String ActivityName, boolean loop) { int filenum = 0; String fileName = ActivityName; File dir = new File(Environment.getExternalStorageDirectory() + "/GetInfoFile/"); String[] dirs = dir.list(); filenum = dirs.length; int num = 0; for (String temp : dirs) { if (temp.contains(ActivityName)) { num = num + 1; } } fileName = ActivityName + "_" + num; try { fileoutputstream = new FileOutputStream( Environment.getExternalStorageDirectory() + "/GetInfoFile/" + (filenum > 9 ? filenum : ("0" + filenum)) + "_" + fileName + ".xml"); filename = (filenum > 9 ? filenum : ("0" + filenum)) + "_" + fileName; printStream = new PrintStream(fileoutputstream); printStream.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); printStream.println("<Activity>"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** * 下载APK文件,返回下载完成的目录 * * @param path * @return */ public static String downLoadApk(String path) { byte[] data = null; HttpGet httpGet = new HttpGet(path); File file = Environment.getExternalStorageDirectory(); FileOutputStream outputStream = null; try { HttpResponse httpResponse = httpClient.execute(httpGet); if (httpResponse.getStatusLine().getStatusCode() == 200) { data = EntityUtils.toByteArray(httpResponse.getEntity()); if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { outputStream = new FileOutputStream(new File(file, Constants.JVE_APK_NAME)); outputStream.write(data, 0, data.length); } } } catch (Exception e) { e.printStackTrace(); } finally { if (outputStream != null) { try { outputStream.close(); } catch (Exception e2) { e2.printStackTrace(); } } } return file.getAbsolutePath() + "/" + Constants.JVE_APK_NAME; }
/** * Returns true if the SD card can be used. Otherwise, returns false. * * @return true if the SD card is available for use. Otherwie, returns false. */ private boolean getSDcardStatus() { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY)) { if (TTS.isSpeaking()) TTS.stop(); // check if keyboard is connected but accessibility services are // disabled if (!Utils.isAccessibilityEnabled(getApplicationContext()) && getResources().getConfiguration().keyboard != Configuration.KEYBOARD_NOKEYS) TTS.speak(getResources().getString(R.string.mediareadonly)); Toast.makeText( getApplicationContext(), getResources().getString(R.string.mediareadonly), Toast.LENGTH_SHORT) .show(); return false; } else { return true; } } if (TTS.isSpeaking()) TTS.stop(); // check if keyboard is connected but accessibility services are // disabled if (!Utils.isAccessibilityEnabled(getApplicationContext()) && getResources().getConfiguration().keyboard != Configuration.KEYBOARD_NOKEYS) TTS.speak(getResources().getString(R.string.mediaunmounted)); Toast.makeText( getApplicationContext(), getResources().getString(R.string.mediaunmounted), Toast.LENGTH_SHORT) .show(); return false; }
@Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.splash); photo = new File(Environment.getExternalStorageDirectory() + "/Frutarre_NoFrames"); Log.d("GCM", photo.toString()); boolean success = false; if (!photo.exists()) { success = photo.mkdirs(); } // if (!success) { Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); photo = new File( Environment.getExternalStorageDirectory() + "/Frutarre_NoFrames", Commons.getTodaysDate() + ".jpg"); Log.d("GCM", photo.toString()); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo)); Uri imageUir = Uri.fromFile(photo); startActivityForResult(intent, REQUEST_CODE); // finish(); } }
public class CONSTANTS { public static final String METADATA_REQUEST_BUNDLE_TAG = "requestMetaData"; public static final String FILE_START_NAME = "VMS_"; public static final String VIDEO_EXTENSION = ".mp4"; public static final String IMAGE_EXTENSION = ".jpg"; public static final String DCIM_FOLDER = "/DCIM"; public static final String CAMERA_FOLDER = "/video"; public static final String TEMP_FOLDER = "/Temp"; public static final String CAMERA_FOLDER_PATH = Environment.getExternalStorageDirectory().toString() + CONSTANTS.DCIM_FOLDER + CONSTANTS.CAMERA_FOLDER; public static final String TEMP_FOLDER_PATH = Environment.getExternalStorageDirectory().toString() + CONSTANTS.DCIM_FOLDER + CONSTANTS.CAMERA_FOLDER + CONSTANTS.TEMP_FOLDER; public static final String VIDEO_CONTENT_URI = "content://media/external/video/media"; public static final String KEY_DELETE_FOLDER_FROM_SDCARD = "deleteFolderFromSDCard"; public static final String RECEIVER_ACTION_SAVE_FRAME = "com.javacv.recorder.intent.action.SAVE_FRAME"; public static final String RECEIVER_CATEGORY_SAVE_FRAME = "com.javacv.recorder"; public static final String TAG_SAVE_FRAME = "saveFrame"; public static final int RESOLUTION_HIGH = 1300; public static final int RESOLUTION_MEDIUM = 500; public static final int RESOLUTION_LOW = 180; public static final int RESOLUTION_HIGH_VALUE = 2; public static final int RESOLUTION_MEDIUM_VALUE = 1; public static final int RESOLUTION_LOW_VALUE = 0; }
public void backup() { Process process = null; DataOutputStream os = null; try { process = Runtime.getRuntime().exec("su"); os = new DataOutputStream(process.getOutputStream()); os.writeBytes("mount -o remount,rw /system\n"); os.writeBytes( "cp -f /system/build.prop " + Environment.getExternalStorageDirectory().getAbsolutePath() + "/build.prop.bak\n"); os.writeBytes("mount -o remount,ro /system\n"); os.writeBytes("exit\n"); os.flush(); process.waitFor(); } catch (Exception e) { log("Error in backup: " + e.getMessage()); } finally { try { if (os != null) { os.close(); } process.destroy(); } catch (Exception e) { log("Error in closing backup process: " + e.getMessage()); } } log( "build.prop Backup at " + Environment.getExternalStorageDirectory().getAbsolutePath() + "/build.prop.bak"); }
public asyncSaveDmesg( Activity clientActivity, List<DmesgLine> list, MenuItem item, boolean blnShare) { this.mActivity = clientActivity; this.mProgressDlg = new ProgressDialog(this.mActivity); this.mListDmesgs = list; this.mItem = item; this.mBlnShare = blnShare; // Are we sharing or saving? String sdState = android.os.Environment.getExternalStorageState(); if (sdState.equals(android.os.Environment.MEDIA_MOUNTED)) { this.mFExternalSDCard = android.os.Environment.getExternalStorageDirectory(); this.mStrFullPath = String.format( "%s/%s", mFExternalSDCard.getPath(), mStrDropFolder.substring( 0, mStrDropFolder.length() - 1)); // chop off trailing slash this.mFSDCardPath = new File(this.mStrFullPath); if (!this.mFSDCardPath.exists()) { if (!this.mFSDCardPath.mkdirs()) { // Red Alert.... Log.w(TAG, String.format("Unable to create %s", this.mStrFullPath)); } } } }
// 获取Android手机中SD卡存储信息 获取剩余空间 public void getSDCardInfo() { // 在manifest.xml文件中要添加 /* * <uses-permission * android:name="android.permission.WRITE_EXTERNAL_STORAGE"> * </uses-permission> */ // 需要判断手机上面SD卡是否插好,如果有SD卡的情况下,我们才可以访问得到并获取到它的相关信息,当然以下这个语句需要用if做判断 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { // 取得sdcard文件路径 File path = Environment.getExternalStorageDirectory(); StatFs statfs = new StatFs(path.getPath()); // 获取block的SIZE long blocSize = statfs.getBlockSize(); // 获取BLOCK数量 long totalBlocks = statfs.getBlockCount(); // 空闲的Block的数量 long availaBlock = statfs.getAvailableBlocks(); // 计算总空间大小和空闲的空间大小 // 存储空间大小跟空闲的存储空间大小就被计算出来了。 long availableSize = blocSize * availaBlock; // (availableBlocks * blockSize)/1024 KIB 单位 // (availableBlocks * blockSize)/1024 /1024 MIB单位 long allSize = blocSize * totalBlocks; } }
/** * 短信的备份 * * @param view */ public void smsBackup(View view) { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { final File file = new File(Environment.getExternalStorageDirectory(), "smsbackup.xml"); final ProgressDialog pd = new ProgressDialog(this); pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); pd.setMessage("稍安勿躁,正在备份中..."); pd.show(); new Thread() { public void run() { try { SmsTools.backup( getApplicationContext(), file.getAbsolutePath(), new BackUpCallBack() { @Override public void onSmsBackup(int progress) { pd.setProgress(progress); } @Override public void beforeSmsBackup(int total) { pd.setMax(total); } }); } catch (Exception e) { e.printStackTrace(); } pd.dismiss(); }; }.start(); } else { Toast.makeText(this, "sd不可用", 0).show(); } }
public static void moveDBtoSD(String name) { try { File sd = Environment.getExternalStorageDirectory(); File data = Environment.getDataDirectory(); if (sd.canWrite()) { String currentDBPath = "//data//org.questionairemanager.engine//databases//" + name; String backupDBPath = name; Log.d("DEBUG", backupDBPath); File currentDB = new File(data, currentDBPath); File backupDB = new File(sd, backupDBPath); if (currentDB.exists()) { FileChannel src = new FileInputStream(currentDB).getChannel(); FileChannel dst = new FileOutputStream(backupDB).getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); } } } catch (Exception e) { Log.d("SD", "Error moviendo la db error:" + e.getMessage()); } }
private void printError( int errorCode, String description, String failingUrl, WWidgetData errorWgt) { try { DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); String time = formatter.format(new Date()); String fileName = time + ".log"; if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { String ePath = Environment.getExternalStorageDirectory().getAbsolutePath(); String path = ePath + "/widgetone/log/pageloaderror/"; File dir = new File(path); if (!dir.exists()) { dir.mkdirs(); } StringBuffer sb = new StringBuffer(); sb.append("failingDes: " + description); sb.append("\n"); sb.append("failingUrl: " + failingUrl); sb.append("\n"); sb.append("errorCode: " + errorCode); sb.append("\n"); if (null != errorWgt) { sb.append(errorWgt.toString()); } FileOutputStream fos = new FileOutputStream(path + fileName); fos.write(sb.toString().getBytes()); fos.flush(); fos.close(); } } catch (Exception e) { e.printStackTrace(); } }
public static File getFileFromServer(String path, ProgressDialog pd) throws Exception { // 如果相等的话表示当前的sdcard挂载在手机上并且是可用的 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); // 获取到文件的大小 pd.setMax(conn.getContentLength()); InputStream is = conn.getInputStream(); File file = new File(Environment.getExternalStorageDirectory(), "updata.apk"); FileOutputStream fos = new FileOutputStream(file); BufferedInputStream bis = new BufferedInputStream(is); byte[] buffer = new byte[1024]; int len; int total = 0; while ((len = bis.read(buffer)) != -1) { fos.write(buffer, 0, len); total += len; // 获取当前下载量 pd.setProgress(total); } fos.close(); bis.close(); is.close(); return file; } else { return null; } }
public void onClickCaptureBtn(View v) { try { String dirName = "YouAndI_Dir"; SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); String imgName = format.format(new Date()); File sdCardPath = Environment.getExternalStorageDirectory(); File dirs = new File(sdCardPath, dirName); if (!dirs.exists()) { dirs.mkdirs(); } capLayout.buildDrawingCache(); Bitmap captureView = capLayout.getDrawingCache(); File img = new File(sdCardPath.getAbsolutePath() + "/" + dirName + "/" + imgName + ".jpeg"); FileOutputStream fos = new FileOutputStream(img); captureView.compress(Bitmap.CompressFormat.JPEG, 100, fos); sendBroadcast( new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + Environment.getExternalStorageDirectory()))); shareImge(img); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private String getOutputMediaFileName() { String state = Environment.getExternalStorageState(); // Check if external storage is mounted if (!Environment.MEDIA_MOUNTED.equals(state)) { Log.e(TAG, "External storage is not mounted!"); return null; } File mediaStorageDir = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "TestingCamera2"); // Create the storage directory if it does not exist if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { Log.e( TAG, "Failed to create directory " + mediaStorageDir.getPath() + " for pictures/video!"); return null; } } // Create a media file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String mediaFileName = mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4"; return mediaFileName; }
// 将图片保存到SD卡中 public static Uri saveImage(Bitmap bitmap) throws FileNotFoundException { // 先判断手机是否装有SD卡,并可以进行读写 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { // Toast.makeText(getApplicationContext(), // "没有SD卡,无法保存图像.", Toast.LENGTH_SHORT).show(); Log.e("ImagesUtil.java", "没有SD卡,无法保存图像."); return null; } // 获得外部SD卡,创建本应用程序的保存目录,保存相片 File sdCard = Environment.getExternalStorageDirectory(); File photoDir = new File(sdCard.getAbsolutePath() + "/mycamera"); Log.i("保存图像地址", photoDir.getAbsolutePath()); if (!photoDir.exists()) { photoDir.mkdirs(); } File photo = new File(photoDir, (new Date()).getTime() + ".jpeg"); FileOutputStream fOut = new FileOutputStream(photo); // 把数据写入文件.下面的100参数表示不压缩 bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut); // 解析图片的Uri,用它传递分享图片 return Uri.parse("file://" + photo.getAbsolutePath()); // Toast.makeText(this,uri.toString(),Toast.LENGTH_LONG).show(); }
/** * 方法描述:createFile方法 * * @param String app_name * @return * @see FileUtil */ public static void createFile(String app_name) { if (android.os.Environment.MEDIA_MOUNTED.equals( android.os.Environment.getExternalStorageState())) { isCreateFileSucess = true; updateDir = new File(Environment.getExternalStorageDirectory() + "/" + KonkaApplication + "/"); updateFile = new File(updateDir + "/" + app_name + ".apk"); if (!updateDir.exists()) { updateDir.mkdirs(); } if (!updateFile.exists()) { try { updateFile.createNewFile(); } catch (IOException e) { isCreateFileSucess = false; e.printStackTrace(); } } } else { isCreateFileSucess = false; } }
public static String getSDCardPath() { String cmd = "cat /proc/mounts"; Runtime run = Runtime.getRuntime(); // 返回与当前 Java 应用程序相关的运行时对象 try { Process p = run.exec(cmd); // 启动另一个进程来执行命令 BufferedInputStream in = new BufferedInputStream(p.getInputStream()); BufferedReader inBr = new BufferedReader(new InputStreamReader(in)); String lineStr; while ((lineStr = inBr.readLine()) != null) { // 获得命令执行后在控制台的输出信息 // Log.i("CommonUtil:getSDCardPath", lineStr); if (lineStr.contains("sdcard") && lineStr.contains(".android_secure")) { String[] strArray = lineStr.split(" "); if (strArray != null && strArray.length >= 5) { String result = strArray[1].replace("/.android_secure", ""); return result; } } // 检查命令是否执行失败。 if (p.waitFor() != 0 && p.exitValue() == 1) { // p.exitValue()==0表示正常结束,1:非正常结束 Log.e("CommonUtil:getSDCardPath", "命令执行失败!"); } } inBr.close(); in.close(); } catch (Exception e) { // Log.e("CommonUtil:getSDCardPath", e.toString()); return Environment.getExternalStorageDirectory().getPath(); } return Environment.getExternalStorageDirectory().getPath(); }
// Generate a String Array that represents all of the files found private String[] getTracks() { if (type == 0) { try { String[] temp = getAssets().list(""); return temp; } catch (IOException e) { e.printStackTrace(); Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show(); } } else if (type == 1) { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) || Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY)) { path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC); path2 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); String[] temp = path.list(); return temp; } else { Toast.makeText( getBaseContext(), "SD Card is either mounted elsewhere or is unusable", Toast.LENGTH_LONG) .show(); } } return null; }
@Override public void uncaughtException(Thread thread, Throwable ex) { final Writer result = new StringWriter(); final PrintWriter printWriter = new PrintWriter(result); // Inject some info about android version and the device, since google can't provide them in the // developer console StackTraceElement[] trace = ex.getStackTrace(); StackTraceElement[] trace2 = new StackTraceElement[trace.length + 3]; System.arraycopy(trace, 0, trace2, 0, trace.length); trace2[trace.length + 0] = new StackTraceElement("Android", "MODEL", android.os.Build.MODEL, -1); trace2[trace.length + 1] = new StackTraceElement("Android", "VERSION", android.os.Build.VERSION.RELEASE, -1); trace2[trace.length + 2] = new StackTraceElement("Android", "FINGERPRINT", android.os.Build.FINGERPRINT, -1); ex.setStackTrace(trace2); ex.printStackTrace(printWriter); String stacktrace = result.toString(); printWriter.close(); Log.e(TAG, stacktrace); // Save the log on SD card if available if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { String sdcardPath = Environment.getExternalStorageDirectory().getPath(); writeLog(stacktrace, sdcardPath + "/vlc_crash"); writeLogcat(sdcardPath + "/vlc_logcat"); } defaultUEH.uncaughtException(thread, ex); }
public void test_createFileIfNecessary() { String fullName = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getAbsolutePath() + "/TestFolder2/fakeFile.txt"; File createdFile = null; try { createdFile = Utils.createFileIfNecessary(fullName); assertNotNull(createdFile); assertTrue(createdFile.getAbsoluteFile() + " is not a file.", createdFile.isFile()); assertTrue(createdFile.canWrite()); File path = createdFile.getParentFile(); assertEquals( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC) .getAbsolutePath() + "/TestFolder2", path.getAbsolutePath()); } catch (IOException e) { assertFalse("IOException while trying to create file: " + e.getMessage(), true); } finally { if (createdFile != null) { //noinspection ResultOfMethodCallIgnored It's a shame if it doesn't get deleted, but not a // huge concern for this test. createdFile.delete(); } } }