How to move an already moved file to new directory - java

I am trying to move a single File between folders. I use file.renameTo() to move my file.
//moving the file to new folder
//this is success
boolean fileMoveCompleted = finalFileToProcess
.renameTo(new File(processingFolderName
+ File.separator + finalFileToProcess.getName()));
//now trying to move the renamed file to another folder
//this is failing
fileMoveCompleted = finalFileToProcess
.renameTo(new File(successFolderName
+ File.separator
+ finalFileToProcess.getName()));
After the first renameTo the file path still points to the older path. Is there any way I can move the same file to another directory ?

You need to keep the first target file of renameTo as reference and rename that one.
File processing = new File(processingFolderName
+ File.separator
+ finalFileToProcess.getName());
boolean fileMoveCompleted = finalFileToProcess.renameTo(processing);
File finished = new File(successFolderName
+ File.separator
+ finalFileToProcess.getName());
fileMoveCompleted = processing.renameTo(finished);
But as File.renameTo's JavaDoc suggests, you should better use Files.move.

Related

How to differentiate between an empty file that has no extension and a directory in java?

Let's suppose I have a zip file containing two elements: elem1 (created by linux command touch elem1) and elem2 (created by linux command mkdir elem2)
Now, in java, I use the following code to extract the content of the zip
// ...
// Suppose we have a valid inputStream on a zip file
// ...
ZipInputStream zipInputStream = new ZipInputStream(inputStream);
ZipEntry entry = zipInputStream.getNextEntry();
while (entry != null) {
int entrySize = (int) entry.getSize();
File file = Paths.get(extractPath).resolve(entry.getName()).toFile();
if (/*Condition to detect a directory*/) {
System.out.println("This is a directory");
FileUtils.forceMkdir(file);
} else if (/*Condition to detect an empty file*/) {
System.out.println("This is an empty file");
} else {
System.out.println("This is something else");
}
entry = zipInputStream.getNextEntry();
}
I would like to specify the right conditions to detect whether entry is a directory, or an empty file without extension. Knowing that these entries are still in memory and do not exist on the filesystem, the command file.isDirectory() always returns false; so I cannot not use it to check for directory.
Any ideas please ?
I created both an empty folder and an empty file without extension and evaluated them with the code below:
public static void main(String[] args) {
String path = System.getProperty("user.home") + File.separator + "Desktop" + File.separator;
File file = new File(path + "EmptyFile");
File folder = new File (path + "EmptyFolder");
System.out.println("Is 'folder' a folder? " + (Files.isDirectory(folder.toPath())? "Yes" : "No" ));
System.out.println("Is 'file' a folder? " + (Files.isDirectory(file.toPath())? "Yes" : "No" ));
}
The (not surprising) result:
Is 'folder' a folder? Yes
Is 'file' a folder? No
The reason why this works is because the function Files.isDirectory(...) looks in the file attributes set by the Operating System to determine whether the item being examined is a "File folder" or simply a "file". My assumption is that Zip programs do not contain such metadata (not even Windows zip). Therefore, "isDirectory" test cannot be performed using the Files.isDirectory(...) function. My quick research discovered that, the way to do this (and I am kind of shocked) is by examining the file name and check to see if the name ends with the file separator. In fact, this is how ZipEntry.isDirectory() works.
Attempting to zip an empty folder is not allowed for Windows zip (maybe allowed with other software?). However, I was able to include empty directories with 7-zip. That wasn't the only difference. The isDirectory() test failed when the zip was created with Windows zip because the file was skipped altogether. So, in order for this to work, create the zip file with zip software other than the one that comes with Windows. Then,
public static void main(String[] args) throws IOException {
String path = System.getProperty("user.home") + File.separator + "Desktop" + File.separator;
FileInputStream inputStream = new FileInputStream(path + "Desktop.zip");
ZipInputStream zipInputStream = new ZipInputStream(inputStream);
ZipEntry entry = zipInputStream.getNextEntry();
while (entry != null) {
File file = Paths.get(entry.getName()).toFile();
if (entry.isDirectory()) {
System.out.println(entry.getName() + " is a directory");
} else if (file.getName().endsWith(".lnk")) {
System.out.println(file.getName() + " is a shortcut");
} else {
System.out.println(entry.getName() + " is a file");
}
entry = zipInputStream.getNextEntry();
}
zipInputStream.close();
}
Outputs for me:
EmptyFile is a file
EmptyFolder/ is a directory
How We Test Wireless Routers _ PCMag_files/ is a directory
How We Test Wireless Routers _ PCMag_files/00hSyhn9j5PNrcOot1tMzz9.1578945749.fit_lim.size_100x100.png is a file
...
etc
One last note... obviously, if a ZipEntry is not a directory, it is a file. Therefore, no else if is needed. That is, unless you would like to make a distinction between file types. In the example above, I wanted to check if a particular file was a shortcut. Just keep in mind that this is not necessary. The logic should only test entries for isDirectory and if the test fails, it is simply a file.

space is replaced by %20 in file path while creating file and file is created at new location

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")) );

Java I/O issue when dealing with files

I'm currently learning Java I/O , when I compile this code :
import java.io.File;
public class Main {public static void main(String[] args){
//Creation of the File object
File f = new File("test.txt");
System.out.println("File absolute path : " + f.getAbsolutePath());
System.out.println("File name : " + f.getName());
System.out.println("Does it exist ? " + f.exists());
System.out.println("Is it a directory? " + f.isDirectory());
System.out.println("Is it a file ? " + f.isFile());
}
The problem is f.exists() and f.isFile()return false
How is that even possible ?
File f = new File("test.txt");
The above line doesn't create an physical file on the disk. it only creates a file object, with the name 'test.txt', thus File#exits() returns false.
You need to create an actual physical file in number of ways.
Using File
file.createNewFile()
using FileWriter
FileWriter writer = new FileWriter(f);
PS: same applies for File#isFile() returning false as well.
File is not a fileā€”it is just a descriptor of a native filesystem resource that may or may not exist. For example, you can do new File(path).createNewFile().
new File("test.txt") It creates a new File instance by converting the given pathname string into an abstract pathname not physical file.
you can call File#createNewFile(). It atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist.
there is nothing wrong with the program except the file location
there are two solutions
1 : you can store the file in the project directory , parallel to src folder
2 you can create the file with full path specified
File f = new File("D:/folder1/folder2/applicationname/src/test.txt");

Replace if a File name exists in a directory

This is the code I tried. But this returns false even if the file exists. The variables FilePath and FileName is obtained from the UI.
File exportFile = new File("\""+FilePath + "\\"+ FileName+"\"");
boolean exists = exportFile.exists();
if (!exists) {
System.out.println("File does not exists");
}
else{
System.out.println( "File exists.");
}
What is the proper way to do this? And BTW, How can I prompt the user to replace or rename the FileName?
replace
File exportFile = new File("\""+FilePath + "\\"+ FileName+"\"");
with
File exportFile = new File(FilePath + "\\" + FileName);
There is no need for quoting the file name. Even if it contains spaces.
I think the problem might be caused by the way you get the file path, since you are getting it from UI, i should point out that you don't have to construct the path, you can either use getAbsolutePath() or getPath() methods provided in the java.io.File class.

Writing to a file without overwriting or appending

I am writing a program in Java where the output is written to a .txt file. Each time I run the program the file is overwritten. I do not want to use the append switch and add data to the file.
I would like to have it so a new file, with the same name, is created each time I run the program. For example, if overflow.txt is the file name, and I run the program three times, the files overflow(1).txt, overflow(2).txt, and overflow(3).txt should be made.
How can this be achieved?
Check if the file exists, if so rename it. Using File.exists and FileUtils.moveFile
You would need to do this recursively until no conflict is found.
Check if the file exists first. If so, modify the name.
String origName = "overflow";
String ext = ".txt";
int num = 1;
file = new File(origName + ext);
while (file.exists()) {
num++;
file = new File(myOrigFileName +"(" + num + ")" + ext);
}
Modify depending on actual requirements. Question is not very clear.
"A new file with the same name" doesn't make sense in most file systems.
In your example, you've got three files with different names:
overflow(1).txt
overflow(2).txt
overflow(3).txt
The bit in brackets is still part of the name. If you want to emulate that behaviour, you'll have to:
Detect the presence of the "plain" filename (if you want to write to that if it doesn't exist)
Start counting at 1, and work out the "new" filename each time by removing the extension, adding the count in brackets, then putting the extension back
Keep counting until you find a filename which doesn't exist
String dirPath = "./";
String fileName = dirPath + "overflow.txt";
if(new File(dirPath + fileName).exist())
{
int counter = 0;
while(new File(dirPath + "overflow(" + ++counter + ").txt").exist());
fileName = "overflow(" + counter + ").txt";
}
When you instanciate the File object, verify if it exists, if it does, just rename it by adding the braces and number, and check again.

Categories