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

How to escape special char in filename

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

清单

        <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>

我的活动

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);

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

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;
}