android - 如何转义文件名中的特殊字符

标签 android android-file

我想在我的应用程序中加载一个文件并将其复制到我的应用程序文件夹中。 但是,当文件名包含空格或特殊字符时,它会失败。 我正在使用过滤器 这是我的代码:

list

        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />

        <data android:scheme="file" />
        <data android:mimeType="*/*" />
        <data android:pathPattern=".*\\.pdf" />
        <data android:host="*" />
    </intent-filter>
</activity>

我的 Activity

Intent intent = getIntent();
if (intent != null) {
    String action = intent.getAction();
    if (action != null && action.compareTo(Intent.ACTION_VIEW) == 0) {
        String scheme = intent.getScheme();
        if (scheme.compareTo(ContentResolver.SCHEME_FILE) == 0) {
            Uri uri = intent.getData();
            String name = uri.getLastPathSegment();

            String filepath = getPath() + name;
            // file name = "test café.pdf"
        }
    }
}

最佳答案

我的一个应用程序中有类似的东西:

 String filepath = getPath() + removeAccents(name);

我做了这个功能,适用于所有 API:

public static String removeAccents(String s){       
    try{    
        s = s.toLowerCase();
        if(VERSION.SDK_INT >  Build.VERSION_CODES.FROYO){
            s = Normalizer.normalize(s, Normalizer.Form.NFD);
            s = s.replaceAll("[^\\p{ASCII}]", "");
        } else{
            s = s.replace("á", "a").replace("é", "e").replace("í", "i").replace("ó", "o").replace("ú", "u").replace("ñ", "n");
        }
    }catch(Exception e){

    }
    return s;
}

关于android - 如何转义文件名中的特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28903202/

相关文章:

Android:检索所有图像目录

android - 是否可以通过我们在 Android 中的应用程序中的代码清除下载管理器应用程序数据

android - CreateTempFile 在图片文件夹中返回没有这样的文件或目录?

android - Android 允许的最大文件路径是多少

android - 玩! Android 客户端的 Framework 2 REST 身份验证和授权

java - 如何使用 Html.fromHtml 在 android 中显示心脏标志

Android Styles 在使用 appcompat-v7 :23. 0.1 时抛出错误

Android PlaceAutocomplete Activity 结果列表文本相互重叠

java - Android不会在文本文件中写入新行

android - 添加新环境时,IBM Worklight Android 的复选框始终处于禁用状态