How can I replace a file name in java I have a file with the following name:
file_1234.dat
I want to change this file to:
file.dat
as well as keep the content of the file as it is.
Thanks
How can I replace a file name in java I have a file with the following name:
file_1234.dat
I want to change this file to:
file.dat
as well as keep the content of the file as it is.
Thanks
You could use regular expressions. Look at the example below... this would only work if your your files follow the _1234 pattern:
String myString = "hello_123.dat"; //you have a string of your choice
System.out.println(myString); //prints the string
String newString = myString.replaceAll("[_\\d]", "");
System.out.println(newString);
So you would get this printed out:
hello_123.dat AND hello.dat
If your file names are "file_XMM1234.dat" You can use the following:
yourString= "file_XMM1234.dat"
String newString = yourString.replaceFirst("_[^.]*", "");
Which will produce: file.dat
You can use regex:
String temp = "file_1234.dat";
temp = temp.replaceAll("_\\d+(?=\\.)", "");
System.out.println(temp);
Use the following
Path source = Paths.get("your/path/file_1234.dat");
Files.move(source, source.resolveSibling((source.getFileName().toString().replaceAll("[_\\d]|[A-Z]", ""))));