import java.io.File;
class PathTruncator {
/**
* Truncates a file path to a specified length, handling edge cases.
*
* @param filePath The original file path.
* @param maxLength The maximum length of the truncated path.
* @return The truncated file path. Returns the original path if it's already shorter than maxLength or if the input is null.
*/
public static String truncatePath(String filePath, int maxLength) {
if (filePath == null) {
return null; // Handle null input
}
if (filePath.length() <= maxLength) {
return filePath; // No truncation needed
}
// Handle paths with trailing slashes
String trimmedPath = filePath.trim();
if (trimmedPath.isEmpty()) {
return ""; // Handle empty path after trimming
}
if (trimmedPath.length() <= maxLength) {
return trimmedPath;
}
return trimmedPath.substring(0, maxLength); // Truncate the path
}
public static void main(String[] args) {
//Example Usage
String path1 = "/path/to/a/very/long/file.txt";
String path2 = "short_path.txt";
String path3 = "";
String path4 = null;
String path5 = "/";
String path6 = "/path/to/a/file.txt";
String path7 = "/path/to/a/very/long/file.txt/";
System.out.println("Original: " + path1 + ", Truncated: " + truncatePath(path1, 20));
System.out.println("Original: " + path2 + ", Truncated: " + truncatePath(path2, 20));
System.out.println("Original: " + path3 + ", Truncated: " + truncatePath(path3, 20));
System.out.println("Original: " + path4 + ", Truncated: " + truncatePath(path4, 20));
System.out.println("Original: " + path5 + ", Truncated: " + truncatePath(path5, 20));
System.out.println("Original: " + path6 + ", Truncated: " + truncatePath(path6, 20));
System.out.println("Original: " + path7 + ", Truncated: " + truncatePath(path7, 20));
}
}
Add your comment