UnKnown UnKnown - 9 days ago 5
Java Question

How to add Special characters to the file name in this case

Before Storing a file i am checking if the file name already exists (to prevent overriding)

For this i am using the following code

import java.io.File;
import java.util.ArrayList;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Test {
public static void main(String[] args) {
String imagename = checkImage("big_buck_bunny.mp4");
System.out.println(imagename);
}

public static String checkImage(String image_name) {
String newimage = "";
ArrayList<String> image_nameslist = new ArrayList<String>();
File file = new File("C:\\Users\\Public\\Videos\\Sample Videos\\");
File[] files = file.listFiles();
for (File f : files) {
image_nameslist.add(f.getName());
}
long l = System.currentTimeMillis();
if (image_nameslist.contains(image_name)) {
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(100);
Matcher matcher = Pattern.compile("(.*)\\.(.*?)").matcher(image_name);
if (matcher.matches()) { // <== test input filename is OK?
newimage = String.format("%s_%d.%s", matcher.group(1),randomInt, matcher.group(2));
}
}
else {
newimage = image_name;
}
return newimage;
}
}


And the output i get is

big_buck_bunny_50.mp4


In place of randomInt in the above code , is it possible to add some special characters @ before and after so that the output looks like\

big_buck_bunny_@50@.mp4

Answer

Just form a string with special characters using your random integer, and then include it in the call to String.format(). The only change I made to your call was to replace %d with %s and to use the random string instead of the random integer.

String randStr = "@" + String.valueOf(randomInt) + "@";
newimage = String.format("%s_%s.%s", matcher.group(1), randStr, matcher.group(2));

But, are you sure that your OS accepts/recommends such file names?

Comments