Java Code Examples for android.os.Environment#getExternalStorageDirectory()

The following examples show how to use android.os.Environment#getExternalStorageDirectory() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: AndroidWeekly   File: FavoriteDao.java    License: Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example 2
Source Project: AndroidProject   File: CameraActivity.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 创建一个拍照图片文件对象
 */
@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;
    }
}
 
Example 3
Source Project: IoTgo_Android_App   File: DirectoryManager.java    License: MIT License 6 votes vote down vote up
/**
 * 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;
}
 
Example 4
Source Project: Multiwii-Remote   File: FileAccess.java    License: Apache License 2.0 6 votes vote down vote up
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();
		}

	}
 
Example 5
Source Project: bubble   File: BrowserFragment.java    License: MIT License 5 votes vote down vote up
@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);
}
 
Example 6
Source Project: AndroidWeekly   File: FavoriteDao.java    License: Apache License 2.0 5 votes vote down vote up
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);
        }
    }
}
 
Example 7
Source Project: Onosendai   File: FiltersPrefFragment.java    License: Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 8
Source Project: Huochexing12306   File: FileUtil.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 9
Source Project: Aceso   File: MainActivity.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 10
/**
 * 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);
}
 
Example 11
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;
    }
}
 
Example 12
/**
 * {@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());
}
 
Example 13
/**
 * ��ȡ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();
}
 
Example 14
@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);
}
 
Example 15
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();
		}
	}
}
 
Example 16
Source Project: Toutiao   File: DownloadUtil.java    License: Apache License 2.0 5 votes vote down vote up
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;
    }
 
Example 17
Source Project: AndPermission   File: StorageReadTest.java    License: Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 18
Source Project: tilt-game-android   File: FileUtils.java    License: MIT License 4 votes vote down vote up
public static String getAbsolutePathOnExternalStorage(final Context pContext, final String pFilePath) {
	return Environment.getExternalStorageDirectory() + "/Android/data/" + pContext.getApplicationInfo().packageName + "/files/" + pFilePath;
}
 
Example 19
private boolean isExternalStoragePath(String filePath) {
    File externalStorageDir = Environment.getExternalStorageDirectory();
    return filePath != null && externalStorageDir != null && filePath.startsWith(externalStorageDir.getPath());
}
 
Example 20
/**
 * 获取外部存储-根目录
 */
public static File getExternalRootDir() {
    return Environment.getExternalStorageDirectory();
}