×

Welcome to TagMyCode

Please login or create account to add a snippet.
2
0
 
0
Language: Java
Posted by: Gerrit Viljoen
Added: Jul 30, 2014 2:45 PM
Views: 24
Add a suffix to the end of the filename but before the extension.

Example:
["test.txt", "_1"] ~> "test_1.txt"
["test", "_1"] ~> "test_1"
[".test", "_1"] ~> ".test_1"
  1.     public static File addSuffix(File file, CharSequence suffix) {
  2.         if (file == null) {
  3.             return null;
  4.         } else if (suffix == null) {
  5.             return file;
  6.         } else {
  7.             return new File(file.getParentFile(), addSuffix(file.getName(), suffix));
  8.         }
  9.     }
  10.  
  11.     public static String addSuffix(CharSequence name, CharSequence suffix) {
  12.         if (name == null) {
  13.             return null;
  14.         } else if (suffix == null) {
  15.             return name.toString();
  16.         } else {
  17.             final int pos = StringUtils.lastIndexOf(name, ".");
  18.             if (pos > 0) {
  19.                 return name.subSequence(0, pos).toString() + suffix + name.subSequence(pos, name.length()).toString();
  20.             } else {
  21.                 return name.toString() + suffix.toString();
  22.             }
  23.         }
  24.     }

1 comment

Excellent!

Write a comment