I am using grails 2.1.1. I want to change a file name on a event. That's why I have attempt some. I just want to rename the file. But my process is not working. Can anyone please help me on this please?!!! Here is my attempt below in controller >>>
String previousFileName = inceptionInstance.fileName
StringBuffer newFileName = new StringBuffer(previousFileName);
int start = 0;
int end = previousFileName.indexOf("_");
newFileName.replace(start, end, params.firmName);
File f = new File(grailsApplication.config.files.location.toString() + File.separatorChar + previousFileName);
f.renameTo( new File( grailsApplication.config.files.location.toString() + File.separatorChar + newFileName) )
I have solved the issue. Just take a look at this ...
new File(grailsApplication.config.files.location.toString() + File.separatorChar + previousFileName).renameTo(new File(grailsApplication.config.files.location.toString() + File.separatorChar + newFileName))
Related
I have installed my software in below mention path.
i am getting resulting path of directory created at different location as my installation path contains space. can some one help me how to resolve this issue.
installation path :
/home/test/glh/QA oist/
expected endpoint reference directory :
/home/test/glh/QA oist/server/Tomcat/webapps/ibis/WEB-INF/services
resulting endpoint reference directory :
/home/test/glh/QA%20oist/server/Tomcat/webapps/ibis/WEB-INF/services
File repDir = new File(axisConf.getRepository().getFile());
String serviceName = IISUtilsHandler.replaceChars(module.getModuleName(), " ", "");
File serviceNameDir = new File(repDir + File.separator + "services" + File.separator + serviceName);
if ((moduleProperties.getBoolProperty("ValidateResponse", false) || moduleProperties.getBoolProperty("ValidateRequest", false))
&& moduleProperties.containsProperty("SchemaFileGenerationError")) {
String schemaGenerationError = moduleProperties.getProperty("SchemaFileGenerationError");
throw new IException("WebServiceConnector.Deploy.ErrorBecauseSchemaGenerationFailed", schemaGenerationError);
}
File serviceDir = new File(serviceNameDir, "META-INF");
if (!serviceDir.mkdirs()) {
throw new InubitException("CreateDirError", serviceDir.toString());
}
IISFileHandler.writeStringToFile(serviceDir + File.separator + "services.xml", createServiceXml(moduleProperties, module));
IISFileHandler.writeStringToFile(serviceDir + File.separator + "service.wsdl", moduleProperties.getProperty("WsdlData"));
Please share more details and sample code you are using to get/generate installation file path.
However you can add below java code to replace special character (%20) with space on the fly
File dir = new File( new URI(installation_path.replaceAll(" ", "%20")) );
i am creating a file and when i create that file, i check if it already exists. If it already exists, i want to create it with the same name, but with the (1) after it. I am able to do that and here is the code :
File apkReceived = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/"+receivedApkName + ".apk");
if(apkReceived.exists()){
apkReceived=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/"+receivedApkName + "(1)"+".apk");
}
byte[] buffer = new byte [8192];
FileOutputStream fos=new FileOutputStream(apkReceived);
then it would continue... (i am writing things on the file).
This works but the problem is that in this situation :
FileTest.apk
FileTest(1).apk
If I receive another Filetest, it will sub my FileTest(1), since it will create it again.
A solution for this would be to check if the file exists again, but then i would have to be doing that for ever.
My goal would be to create (1) and then (2) , etc.
Does any one of you know how to do this ?
EDIT: Obviously i could use a cicle to check it. The problem is on how to get the (1) and then the (2) and don't get the (1)(2)
To avoid reinventing the wheel I suggest using Timestamp it hardly ever will have collisions.
java.util.Date date= new java.util.Date();
Timestamp tstamp = new Timestamp(date.getTime());
File apkReceived = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/"+receivedApkName + tstamp + ".apk");
Do Something like this
File apkReceived = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/"+receivedApkName + ".apk");
if(apkReceived.exists()){
int new_int_postfix;
//Below _MAX is max numbers of file eg. _MAX = 100
for(int i = 1; i < _MAX; i++) {
apkReceived = = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/"+receivedApkName +"("+ i +")"+".apk");
if(!apkReceived.exists()) {
String []name_without_pre = receivedApkName.split("\\(");
receivedApkName = name_without_pre[0];
new_int_postfix = i;
break;
}
}
apkReceived = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/"+receivedApkName + "("+new_int_postfix+")"+".apk");
}
byte[] buffer = new byte [8192];
FileOutputStream fos=new FileOutputStream(apkReceived);
Some pseudocode to get you started:
Fetch a list of all files in the directory
For the one you want to copy: check if you already have one or more copies
If you already have "file_(n)"; use "file_(n+1)" as new filename.
Obviously: you should clarify your requirements on the "maximum" n you want to allow; and what to happen when n copies were created; and another is asked for.
If you only store that one type of file in your directory you can do:
File folder = new File("your/path");
File[] listOfFiles = folder.listFiles();
count the size and size + 1 for your next filename.
you can also separate each file with similiar filename on their own directory.
try this
String filename =Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/"+receivedApkName + ".apk";
File f = new File(filename);
String extension = ".apk";
int g = 0;
while(f.exists()) {
int i = f.lastIndexOf('.');
if (i > 0)
{ extension = fileName.substring(i+1); }
f.renameTo(f.getPath() + "\" + (f.getName() + g) + "." + extension)
}
Here i'm able to change the name of image but for the new image i'm not getting the same image as first one.
Here my initial image is ABC.png and new image is XYZ.png i'm able to change the image name from ABC.png to XYZ.png but i need XYZ.png as similar to ABC.png just i need to change name of image.
Here is my code
File prevfile = new File(ImagesPath + "/" + oldvalue + ".png");
File nextfile = new File(ImagesPath + "/" + newValue + ".png");
prevfile.renameTo(nextfile);
File prevfile = new File(ImagesPath + "/" + oldvalue + ".png");
File nextfile = new File(ImagesPath + "/" + newValue + ".png");
//prevfile.renameTo(nextfile);
Rather than renameTo function better use
FileUtils.copyFile(prevfile , nextfile );
prevfile .delete();
Rename Image with new name and delete previous name.
I am trying to create a file, but file path is constructed through String Concats that uses some internal variables and labels, I am getting following error :
Exception in thread "main" java.io.IOException: The filename, directory name, or volume label syntax is incorrect
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(Unknown Source)
at CopyEJ.CopyEJ.main(CopyEJ.java:133)
Is there a standard approach to built such files ?
String s_path = text_dir + "\\" + time_stmp + "_" + "Session" + "_" + file_name;
File ssw = new File(s_path);
ssw.createNewFile(); //Errors Out here
You need to create the folder (directory) first:
String s_path = text_dir + "/" + time_stmp + "_" + "Session" + "_" + file_name;
File ssw = new File(s_path);
ssw.getParentFile().mkdirs();
ssw.createNewFile();
This will help you:
String path = "D://abc" + filename+ ".txt";
System.out.println("Path--- " + path);
File file = new File(path);
file.createNewFile()
If You are using Java 1.7 you can rewrite it as follows:
Path s_path = Paths.get(text_dir, time_stmp + "_" + "Session" + "_" + file_name);
Files.createDirectories(s_path.getParent());
File ssw = s_path.toFile();
ssw.createNewFile();
Paths.get() will use default system path separator.
I want to add an index to a filename if the file already exists, so that I don't overwrite it.
Like if I have a file myfile.txt and same time myfile.txt exists in destination folder - I need to copy my file with name myfile_1.txt
And same time if I have a file myfile.txt, but destintation folder contains myfile.txt and myfile_1.txt - generated filename has to be myfile_2.txt
So the functionality is very similar to the creation of folders in Microsoft operating systems.
What's the best approach to do that?
Using commons-io:
private static File getUniqueFilename( File file )
{
String baseName = FilenameUtils.getBaseName( file.getName() );
String extension = FilenameUtils.getExtension( file.getName() );
int counter = 1
while(file.exists())
{
file = new File( file.getParent(), baseName + "-" + (counter++) + "." + extension );
}
return file
}
This will check if for instance file.txt exist and will return file-1.txt
You might also benefit from using the apache commons-io library. It has some usefull file manipulation methods in class FileUtils and FilenameUtils.
Untested Code:
File f = new File(filename);
String extension = "";
int g = 0;
int i = f.lastIndexOf('.');
extension = fileName.substring(i+1);
while(f.exists()) {
if (i > 0)
{ f.renameTo(f.getPath() + "\" + (f.getName() + g) + "." + extension); }
else
{ f.renameTo(f.getPath() + "\" + (f.getName() + g)); }
g++;
}
Try this link partly answers your query.
https://stackoverflow.com/a/805504/1961652
DirectoryScanner scanner = new DirectoryScanner();
scanner.setIncludes(new String[]{"**/myfile*.txt"});
scanner.setBasedir("C:/Temp");
scanner.setCaseSensitive(false);
scanner.scan();
String[] files = scanner.getIncludedFiles();
once you have got the correct set of files, append a proper suffix to create a new file.