下面列出了android.os.Environment#getExternalStorageDirectory ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void exportToFile() throws IOException {
List<Favorite> all = read();
String json = JsonUtil.toJson(all);
File file = new File(Environment.getExternalStorageDirectory(), "androidweeklyfavorite.json");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(file);
fileWriter.write(json);
fileWriter.flush();
} finally {
IOUtil.close(fileWriter);
}
}
/**
* 创建一个拍照图片文件对象
*/
@SuppressWarnings("ResultOfMethodCallIgnored")
private static File createCameraFile() {
File folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "Camera");
if (!folder.exists() || !folder.isDirectory()) {
if (!folder.mkdirs()) {
folder = Environment.getExternalStorageDirectory();
}
}
try {
File file = new File(folder, "IMG_" + new SimpleDateFormat("yyyyMMdd_kkmmss", Locale.getDefault()).format(new Date()) + ".jpg");
file.createNewFile();
return file;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* Determine if a file or directory exists.
* @param name The name of the file to check.
* @return T=exists, F=not found
*/
public static boolean testFileExists(String name) {
boolean status;
// If SD card exists
if ((testSaveLocationExists()) && (!name.equals(""))) {
File path = Environment.getExternalStorageDirectory();
File newPath = constructFilePaths(path.toString(), name);
status = newPath.exists();
}
// If no SD card
else {
status = false;
}
return status;
}
public FileAccess(String fileName) {
root = Environment.getExternalStorageDirectory();
file = new File(root, fileName);
try {
Log.d("plik", file.toString());
filewriter = new FileWriter(file);
out = new BufferedWriter(filewriter);
Log.d("plik", "fileAccess OK");
} catch (IOException e) {
Log.d("plik", "fileAccess ERR");
// Toast.makeText(context, "Can't write to file",
// Toast.LENGTH_LONG).show();
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mCurrentDir = (File) savedInstanceState.getSerializable(STATE_CURRENT_DIR);
}
else {
mCurrentDir = Environment.getExternalStorageDirectory();
}
getActivity().setTitle(R.string.menu_browser);
}
public void importFromFile() throws IOException {
File file = new File(Environment.getExternalStorageDirectory(), "androidweeklyfavorite.json");
String json = IOUtil.read(file);
List<Favorite> favorites = JsonUtil.fromJson(json, new TypeToken<List<Favorite>>() {
}.getType());
if (favorites != null) {
for (Favorite favorite : favorites) {
save(favorite);
}
}
}
private void startFileWrite () {
final File file = new File(Environment.getExternalStorageDirectory(),
FILTERS_FILE_PREFIX
+ DateHelper.standardDateTimeFormat().format(new Date())
+ FILTERS_FILE_EXT);
new FileWriteTask(FiltersPrefFragment.this, getPrefs(), file).execute();
}
public static File getSDParentDir() throws IOException{
if (isSDCardExist()){
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "HuoCheXing");
if (!file.exists()){
file.mkdir();
}
return file;
}
return null;
}
public void fix(View view) {
File patchFile = new File(Environment.getExternalStorageDirectory(), "fix.apk");
if (!patchFile.exists()) {
Toast.makeText(this, "hotfix file not exist!", Toast.LENGTH_SHORT).show();
return;
}
File optDir = new File(this.getFilesDir(), "fix_opt");
optDir.mkdirs();
new Aceso().installPatch(optDir, patchFile);
}
/**
* Checks if there is enough Space on SDCard
*
* @param updateSize size to Check (long)
* @return <code>true</code> if the Update will fit on SDCard, <code>false</code> if not enough
* space on SDCard. Will also return <code>false</code>, if the SDCard is not mounted as
* read/write
*/
public boolean hasEnoughSpaceOnSdCard(long updateSize)
{
RootTools.log("Checking SDcard size and that it is mounted as RW");
String status = Environment.getExternalStorageState();
if (!status.equals(Environment.MEDIA_MOUNTED))
{
return false;
}
File path = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
return (updateSize < availableBlocks * blockSize);
}
private boolean exportWallet(Activity c, boolean already) {
if (walletToExport == null)
return false;
if (walletToExport.startsWith("0x"))
walletToExport = walletToExport.substring(2);
if (ExternalStorageHandler.hasPermission(c)) {
File folder = new File(Environment.getExternalStorageDirectory(), "Lunary");
if (!folder.exists())
folder.mkdirs();
File storeFile = new File(folder, walletToExport + ".json");
try {
copyFile(new File(c.getFilesDir(), walletToExport), storeFile);
} catch (IOException e) {
return false;
}
// fix, otherwise won't show up via USB
Intent mediaScannerIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri fileContentUri = Uri.fromFile(storeFile); // With 'permFile' being the File object
mediaScannerIntent.setData(fileContentUri);
c.sendBroadcast(mediaScannerIntent); // With 'this' being the context, e.g. the activity
return true;
} else if (!already) {
ExternalStorageHandler.askForPermission(c);
return exportWallet(c, true);
} else {
return false;
}
}
/**
* {@inheritDoc}
*/
@Override
public void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException {
ServerConfig serverConfig = (ServerConfig) getServletContext().getAttribute(ServerConfig.class.getName());
HTMLDocument doc = new HTMLDocument("Drive Access");
doc.setOwnerClass(getClass().getSimpleName());
doc.writeln("<div class=\"page-header\"><h1>Drive Access</h1></div>");
if (!serverConfig.getAttribute(ADMIN_DRIVE_ACCESS_ENABLED).equals(ServerConfigImpl.TRUE)) {
renderFunctionDisabled(response, doc);
return;
}
String path = StringUtilities.urlDecode(request.getQueryString());
if ("".equals(path)) {
path = "/";
}
renderBreadcrubms(doc, path);
File file = new File(Environment.getExternalStorageDirectory() + path);
if (file.exists() && file.isDirectory()) {
renderDirectoryList(doc, path, file);
} else {
renderPathNotAvailable(doc);
}
response.getWriter().print(doc.toString());
}
/**
* ��ȡSD���Ŀ��ÿռ�
* @param view
*/
public void space(View view){
File file = Environment.getExternalStorageDirectory();
long size = file.getFreeSpace(); //byte
String formatFileSize = Formatter.formatFileSize(this, size);
Toast.makeText(this, formatFileSize, 0).show();
}
@Override
public void onCreate(Bundle bdl) {
super.onCreate(bdl);
PermissionUtils.get(this).needStorage(this);
setContentView(R.layout.settings_backuprestore);
ListView list = findViewById(R.id.listView1);
mFolder = new File(Environment.getExternalStorageDirectory(), "backups/com.metinkale.prayer");
mFolder.mkdirs();
mAdapter = new MyAdapter(this);
list.setAdapter(mAdapter);
list.setOnItemClickListener(this);
}
public static void createSDCardDir(boolean isCreateVideoDir) {
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
File sdcardDir = Environment.getExternalStorageDirectory();
String path = sdcardDir.getPath() + VIDEO_THUMB_PATH;
File path1 = new File(path);
if (!path1.exists()) {
path1.mkdirs();
}
}
}
public static Boolean saveImage(String url, Context context) {
boolean flag = false;
try {
// 获取 bitmap
Bitmap bitmap = Glide.with(context).asBitmap().load(url)
.submit(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
.get();
// http://stormzhang.com/android/2014/07/24/android-save-image-to-gallery/
if (bitmap != null) {
// 首先保存图片
File appDir = new File(Environment.getExternalStorageDirectory(), "Toutiao");
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + ".jpg";
File file = new File(appDir, fileName);
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
// 其次把文件插入到系统图库
// MediaStore.Images.Media.insertImage(InitApp.AppContext.getContentResolver(), file.getAbsolutePath(), fileName, null);
// 最后通知图库更新
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
flag = true;
}
} catch (InterruptedException | ExecutionException | IOException e) {
ErrorAction.print(e);
return false;
}
return flag;
}
@Override
public boolean test() throws Throwable {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && !Environment.isExternalStorageLegacy()) return true;
if (!TextUtils.equals(Environment.MEDIA_MOUNTED, Environment.getExternalStorageState())) return true;
File directory = Environment.getExternalStorageDirectory();
if (!directory.exists()) return true;
long modified = directory.lastModified();
String[] pathList = directory.list();
return modified > 0 && pathList != null;
}
public static String getAbsolutePathOnExternalStorage(final Context pContext, final String pFilePath) {
return Environment.getExternalStorageDirectory() + "/Android/data/" + pContext.getApplicationInfo().packageName + "/files/" + pFilePath;
}
private boolean isExternalStoragePath(String filePath) {
File externalStorageDir = Environment.getExternalStorageDirectory();
return filePath != null && externalStorageDir != null && filePath.startsWith(externalStorageDir.getPath());
}
/**
* 获取外部存储-根目录
*/
public static File getExternalRootDir() {
return Environment.getExternalStorageDirectory();
}