1. import java.io.File;
  2. class PathTruncator {
  3. /**
  4. * Truncates a file path to a specified length, handling edge cases.
  5. *
  6. * @param filePath The original file path.
  7. * @param maxLength The maximum length of the truncated path.
  8. * @return The truncated file path. Returns the original path if it's already shorter than maxLength or if the input is null.
  9. */
  10. public static String truncatePath(String filePath, int maxLength) {
  11. if (filePath == null) {
  12. return null; // Handle null input
  13. }
  14. if (filePath.length() <= maxLength) {
  15. return filePath; // No truncation needed
  16. }
  17. // Handle paths with trailing slashes
  18. String trimmedPath = filePath.trim();
  19. if (trimmedPath.isEmpty()) {
  20. return ""; // Handle empty path after trimming
  21. }
  22. if (trimmedPath.length() <= maxLength) {
  23. return trimmedPath;
  24. }
  25. return trimmedPath.substring(0, maxLength); // Truncate the path
  26. }
  27. public static void main(String[] args) {
  28. //Example Usage
  29. String path1 = "/path/to/a/very/long/file.txt";
  30. String path2 = "short_path.txt";
  31. String path3 = "";
  32. String path4 = null;
  33. String path5 = "/";
  34. String path6 = "/path/to/a/file.txt";
  35. String path7 = "/path/to/a/very/long/file.txt/";
  36. System.out.println("Original: " + path1 + ", Truncated: " + truncatePath(path1, 20));
  37. System.out.println("Original: " + path2 + ", Truncated: " + truncatePath(path2, 20));
  38. System.out.println("Original: " + path3 + ", Truncated: " + truncatePath(path3, 20));
  39. System.out.println("Original: " + path4 + ", Truncated: " + truncatePath(path4, 20));
  40. System.out.println("Original: " + path5 + ", Truncated: " + truncatePath(path5, 20));
  41. System.out.println("Original: " + path6 + ", Truncated: " + truncatePath(path6, 20));
  42. System.out.println("Original: " + path7 + ", Truncated: " + truncatePath(path7, 20));
  43. }
  44. }

Add your comment