Generate Random file name in Java
You can create a random string for a file name using following code snippet.
public static String getRandomString(String fileName) {
char fileNameArray[] = fileName.toCharArray();
int fileNameLen = fileNameArray.length;
int c = 'A';
int r1 = 0, z=0;
StringBuilder pw = new StringBuilder("");
for (int j = 0; j < 25; j++) {
r1 = (int) (Math.random() * 4);
switch (r1) {
case 0:
c = '0' + (int) (Math.random() * 9);
if (c>'9'){
z = reset(z,fileNameLen);
c = fileNameArray[z];
}
break;
case 1:
c = 'a' + (int) (Math.random() * 25);
if (c<'a' && c>'z'){
z = reset(z,fileNameLen);
c = fileNameArray[z];
}
break;
case 2:
c = 'A' + (int) (Math.random() * 25);
if (c<'A' && c>'Z'){
z = reset(z,fileNameLen);
c = fileNameArray[z];
}
break;
}
pw.append((char) c);
}
fileNameArray = null;
String s="";
try{
s =fileName.substring(fileName.lastIndexOf("."));
if (s.equalsIgnoreCase(".tmp")){
s=".jpg";
}
}catch(ArrayIndexOutOfBoundsException arrayExp){
s="";
}
return new String(pw+s.trim());
}
private static int reset(int z, int len){
if (z>=len){
z=0;
}
return z;
}
public static String getRandomString(String fileName) {
char fileNameArray[] = fileName.toCharArray();
int fileNameLen = fileNameArray.length;
int c = 'A';
int r1 = 0, z=0;
StringBuilder pw = new StringBuilder("");
for (int j = 0; j < 25; j++) {
r1 = (int) (Math.random() * 4);
switch (r1) {
case 0:
c = '0' + (int) (Math.random() * 9);
if (c>'9'){
z = reset(z,fileNameLen);
c = fileNameArray[z];
}
break;
case 1:
c = 'a' + (int) (Math.random() * 25);
if (c<'a' && c>'z'){
z = reset(z,fileNameLen);
c = fileNameArray[z];
}
break;
case 2:
c = 'A' + (int) (Math.random() * 25);
if (c<'A' && c>'Z'){
z = reset(z,fileNameLen);
c = fileNameArray[z];
}
break;
}
pw.append((char) c);
}
fileNameArray = null;
String s="";
try{
s =fileName.substring(fileName.lastIndexOf("."));
if (s.equalsIgnoreCase(".tmp")){
s=".jpg";
}
}catch(ArrayIndexOutOfBoundsException arrayExp){
s="";
}
return new String(pw+s.trim());
}
private static int reset(int z, int len){
if (z>=len){
z=0;
}
return z;
}
Comments
Post a Comment