Android:消除文件路径

前端之家收集整理的这篇文章主要介绍了Android:消除文件路径前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我的应用程序中,用户选择文件.在内部,我存储有关该文件的信息,我根据文件路径键.下次使用该文件时,我会使用存储的信息进行填充.我的例子是:

File file1 = new File(Environment.getExternalStorageDirectory()“/test.txt”);

然后,在特定的JB设备上,file1.getCanonicalPath()给出:“/storage/emulated/0/test.txt”.

麻烦的是,当其他应用程序使用Intent中的文件路径启动我的应用程序时,它们发送的路径往往如下所示:“/mnt/sdcard/test.txt”.

有没有一个明智的策略去消除这两条路?可能我应该实例化我的文件不同?

编辑:

麻烦的是,两个文件的两个通道不一样.对于下面的cp1 ==“mnt / sdcard / test / txt”和cp2 ==“/ storage / emulated / 0 / text / txt”:

File file1 = new File("/mnt/sdcard/test.txt");
File file2 = new File("/storage/emulated/0/test.txt");

String cp1 = file1.getCanonicalPath();
String cp2 = file2.getCanonicalPath();

解决方法

首先,获取外部路径的唯一正确方法是使用Android中的getExternalStorageDirectory和其他getExternalStorageXXX.

Android将首先尝试解析两个系统变量:

String rawExternalStorage = System.getenv(ENV_EXTERNAL_STORAGE);
String rawEmulatedStorageTarget = System.getenv(ENV_EMULATED_STORAGE_TARGET);

而ENV_EXTERNAL_STORAGE =“EXTERNAL_STORAGE”和ENV_EMULATED_STORAGE_TARGET =“EMULATED_STORAGE_TARGET”.如果设置了EMULATED_STORAGE_TARGET变量,则表示设备已经模拟存储,那么存储路径将是EMULATED_STORAGE_TARGET(Android 4.2之后,它支持用户外部存储,那么在路径后面会有一个/ 0或0)但是如果没有设置EXTERNAL_STORAGE,路径将为EXTERNAL_STORAGE.如果两者都未设置,默认情况下路径为/ storage / sdcard0.因此,不同的设备可能包含不同的外部存储路径.

External Storage Technical Information所示,您可以通过设置init.rc文件自定义设备的存储.例如在默认的金鱼之一:

export EXTERNAL_STORAGE /mnt/sdcard
mkdir /mnt/sdcard 0000 system system
symlink /mnt/sdcard /sdcard

如果使用getExternalStorageDirectory,您将获得/ mnt / sdcard,但是/ sdcard是到该目录的符号链接.

所以在你的情况下,init.rc可能包含:

export EMULATED_STORAGE_TARGET /storage/emulated
symlink /storage/emulated/0 /mnt/sdcard

所以他们并不模糊,他们实际上是一样的.

我认为getCanonicalPath()可能适用于绝大多数的用例.

A canonical pathname is both absolute and unique. The precise
definition of canonical form is system-dependent. This method first
converts this pathname to absolute form if necessary,as if by
invoking the getAbsolutePath() method,and then maps it to its unique
form in a system-dependent way. This typically involves removing
redundant names such as “.” and “..” from the pathname,resolving
symbolic links (on UNIX platforms),and converting drive letters to a
standard case (on Microsoft Windows platforms).

Every pathname that denotes an existing file or directory has a unique canonical form. Every pathname that denotes a nonexistent file or directory also has a unique canonical form. The canonical form of the pathname of a nonexistent file or directory may be different from the canonical form of the same pathname after the file or directory is created. Similarly,the canonical form of the pathname of an existing file or directory may be different from the canonical form of the same pathname after the file or directory is deleted.

原文链接:https://www.f2er.com/android/311267.html

猜你在找的Android相关文章