Created
January 4, 2024 18:57
-
-
Save maxmpz/dab88451c0f54c6851074e7146cd5b8d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @return same name StringBuilder returned | |
*/ | |
public static @NonNull StringBuilder sanitizeFilenameMutate(@NonNull StringBuilder name) { | |
return sanitizeFilenameMutate(name, 0, Integer.MAX_VALUE); // NOTE: end is checked vs name.length anyway | |
} | |
/** | |
* @param end can be -1 to process to end | |
* @return same name StringBuilder returned | |
*/ | |
public static @NonNull StringBuilder sanitizeFilenameMutate(@NonNull StringBuilder name, int start, int end) { | |
if(end < 0 || end >= name.length()) { | |
end = name.length() - 1; | |
} | |
for(int i = start; i <= end; i++) { | |
char c = name.charAt(i); | |
if(!Character.isLetterOrDigit(c) && c != ' ' && c != '-' && c != '$' && c != '@' && c != '!' && c != '=' && c != '.' && c != ',') { | |
name.setCharAt(i, '_'); | |
} | |
} | |
return name; | |
} | |
/** | |
* Supports content:// paths as well | |
*/ | |
public static @Nullable String getNameWithoutNumber(@Nullable String path) { | |
if(path == null || path.length() == 0) { | |
return path; | |
} | |
boolean isContent = isContentPath(path); | |
int start = 0; | |
int lastSlashIx = path.lastIndexOf('/'); | |
if(lastSlashIx != -1) { | |
start = lastSlashIx + 1; | |
} | |
final int len = path.length(); | |
for(; start < len; start++) { | |
char ch = path.charAt(start); | |
if(!(ch < 'A' || ch == '_')) { | |
break; | |
} | |
} | |
int dotPos = path.lastIndexOf('.'); | |
if(dotPos != -1 && dotPos > start) { | |
path = path.substring(start, dotPos); | |
} | |
if(isContent) { | |
path = Uri.decode(path); | |
} | |
return path; | |
} | |
public static boolean isContentPath(String path) { | |
return path.length() > 8 | |
&& path.charAt(0) == 'c' | |
&& path.charAt(1) == 'o' | |
&& path.charAt(2) == 'n' | |
&& path.charAt(3) == 't' | |
&& path.charAt(4) == 'e' | |
&& path.charAt(5) == 'n' | |
&& path.charAt(6) == 't' | |
&& path.charAt(7) == ':'; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment