-4

How to append text to a existing filename using Java selenium.

Example : Current filename : 19062306.csv

      New filename : 19062306 ABC.csv

package package1;

import java.io.File;
import java.util.Arrays;

import org.apache.commons.io.FilenameUtils;

public class Rename {

public static void main(String[] args) {
File f = null;
      String[] paths;        
      try {    
         f = new File("E:\\HCA_Automation\\Files");
         paths = f.list();    
         for(String path:paths) {
            System.out.println(path);
            String[] array = path.split("."); 

            System.out.println("input string: " + path);
            System.out.println("output array after splitting with . : " + Arrays.toString(array));

            array = path.split("\\.");
            System.out.println("input string: " + path);
            System.out.println("output array after splitting with regex'\\.' : " + Arrays.toString(array));

            array = path.split("[.]");
            System.out.println("input string: " + path);
            System.out.println("output array after splitting with regex '[.]' : " + Arrays.toString(array));

            String filename = array[0];
            String extension = array[1];

            System.out.println("file: " + path);
            System.out.println("name: " + filename);
            System.out.println("extension: " + extension);

            //String base = FilenameUtils.removeExtension(filename);
            //extension = FilenameUtils.getExtension(filename);
           String result = filename + " PAS"  + "." +extension;
           System.out.println(result);
         }  

      } 
       catch(Exception e) {
       e.printStackTrace();
      }
   }

}

When I'm trying to execute the above code it's renaming the file when I'm doing SOP but when I'm checking in the folder the file has not been renamed. Can somebody help me.

Begginer
  • 317
  • 2
  • 3
  • 13
  • Possible duplicate of [Rename a file using Java](https://stackoverflow.com/questions/1158777/rename-a-file-using-java) – Kamal Jun 25 '19 at 07:57

1 Answers1

2

This is simple Java programing, irrespective of Selenium:

  1. Split the file into the main part and the suffix. Hint: find the position of the right-most . character. Or use String::split.
  2. Append the text to the main part. Hint: use string concatenation.
  3. Reassemble the (new) main part and suffix to produce the new filename. Hint: see previous hint.
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • I am not sure how to append the text to the filename.Can you help me in that. – Begginer Jun 25 '19 at 07:49
  • Hi, I have written the code and it's renaming the file also but only in console and not in the folder as in when I am doing SOP it's giving me the required output but when I am checking the folder there no changes has been done to filename. I have updated the code in the question, can you please have a look to it. – Begginer Jun 25 '19 at 15:50