Replace if a File name exists in a directory - java

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.

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.

File.exists() Method always returns true even when the file doesn't exist

Im trying to curb duplicate downloads by checking if the file a user is about to download already exists before I proceed to downloading it.
Im using the method File.exists() to check for this condition but it seems to be always returning true.
Below is my code:
File destination = new File(Environment.DIRECTORY_DOWNLOADS, "/" + playlistTitle + "/" + image.getImgTitle() + ".jpg");
if (!destination.exists()) {
downloadId = downloadImage(image.getImgURL(), image.getImgTitle(), playlistTitle);
downloadIds.add(downloadId);
}
If I go directly to that file path before its created, it seems to be empty, but the code above returns true regardless.
You can check few things here
first as expected we are getting the permission to read and write the storage media.
and you try also using below method for checking if a file can be read or not
if (!file.canRead()) {
return false;
}
if two above doesn't work then use this.
if (!file.isFile()) {
//file doesn't exist
}else{
//file exists
}
new File(Environment.DIRECTORY_DOWNLOADS, "/" + playlistTitle
That can only lead to a path that is not possible.
You should use instead
new File( Environment.getExternalPublicDirectory(
Environment.DIRECTORY_DOWNLOADS),......

How to move an already moved file to new directory

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.

How To Give A Random File Name To File , Which i am Uploading? [duplicate]

This question already has answers here:
How to generate a random alpha-numeric string
(46 answers)
Closed 5 years ago.
I am uploading a file to a folder , i had given the file name as "1.jpg" , so when i am uploading a new file it will overwrite the existing one,
So How i can give a random file name to the file which i am uploading
MY UPLOAD CODE IS HERE
#RequestMapping(value = "/event/uploadFile",headers=("content-type=multipart/*"), method = RequestMethod.POST,consumes ={"application/x-www-form-urlencoded"})
//String quote_upload=C:\fakepath\images.jpg
public #ResponseBody
String uploadFileHandler(
#RequestParam MultipartFile file) {
System.out.println("Creating the directory to store file");
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
// Creating the directory to store file
String rootPath = System.getProperty("catalina.home");
File dir = new File(rootPath + File.separator + "tmpFiles");
if (!dir.exists())
dir.mkdirs();
// Create the file on server
File serverFile = new File(dir.getAbsolutePath()
+ File.separator+"1.jpg");
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
System.out.println("************Server File Location="
+ serverFile.getAbsolutePath());
//return "You successfully uploaded file=" + name;
} catch (Exception e) {
System.out.println("************failes"+ e.getMessage());
//return "You failed to upload " + name + " => " + e.getMessage();
}
//return "You failed to upload " + name
//+ " because the file was empty.";
}
System.out.println("hello");
return "hello";
}
If you do not expect the names to have any sensible order, I would probably go with UUID. Something like this should do it:
String filename = UUID.randomUUID().toString();
If you're worried about uniqueness of the UUID, have a look at this thread. In short, you are extremely unlikely to ever get two ids that are the same.
Generate a Random Name for your newly uploaded file
String fileName = UUID.randomUUID().toString()+YOUR_FILE_EXTENSION;
Check if File exist in the directory you are uploading
if(serverFile.exists())
If File Exist start again from step 1 until you get a file name which is not present in the server.
Note: This is not the optimal solution but will fulfill your requirement.
You can use
Calendar.getInstance().getTimeInMillis();
It will return the time in milliseconds.
If you are not sure about this append some random number to it.
You may use:
File.createTempFile(String prefix, String suffix, File directory)
As the JavaDoc states:
Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name. If this method returns successfully then it is guaranteed that:
The file denoted by the returned abstract pathname did not exist before this method was invoked, and
Neither this method nor any of its variants will return the same abstract pathname again in the current invocation of the virtual machine.
You can simply get a random large integer and give your file that name, like so:
String fileExtension = ".jpg";
String fileName = Integer.toString(new Random().nextInt(1000000000)) + fileExtension;

Move one folder from one place to another one

I am trying to move one folder from c:\root to a different place, let's say, directly to the project folder by using the code below. The variable newFolder is declared as class variable and it has been used in another method where user can rename folder to a different name and it holds the name of the folder that I want to move. The variable fileManager is for a new folder where I want to move my folder. When I run this code I always get "Folder " + fileManager.getName() + " is not moved.". So for some reason it skips if condition and goes to else without moving the folder where I want. Can some one show me how to modify my code in order to move one folder from one place to another one?
File fileManager = new File(newFolder.getName());
try{
if(fileManager.renameTo(new File(fileManager.getName()))){
System.out.println("Folder " + fileManager.getName() + " is moved.");
}else{
System.out.println("Folder " + fileManager.getName() + " is not moved.");
}
}catch(Exception ex){
System.out.println("Error - Folder not found!");
}
You need to call renameTo() on the existing file.
Your code currently is trying to rename the new folder (fileManager) to something, but the new folder (probably) does not exist on your filesystem so it returns false because there is nothing to rename.
Actually, I can't see anything that looks like the original file handle anywhere in this code, but you are going to need the original file in order to rename it.
Your code actually does nothing since it just renames a file to itself:
fileManager.renameTo(new File(fileManager.getName())
I am not sure whether this would return true or false if the file exists already on the OS. Does it count as a "successful rename" if you rename a file to itself?
You probably want something that looks more like this (guessing variable names):
oldFileOrFolder.renameTo(fileManager)
I also got rid of the new File constructor since your object already is of type File.
I would use the Files.move method instead, I had no issues with it. Below is an example using a file instead of a folder.
static File fileManager = new File("C:\\template.xls");
public static void main(String[] args) throws IOException {
Path originalPath = Paths.get(fileManager.getPath());
Path newPath = Paths.get(System.getProperty("user.dir")+ "\\template.xls");
if(Files.move(originalPath, newPath , StandardCopyOption.REPLACE_EXISTING) != null){
System.out.println("Folder " + fileManager.getName() + " is moved.");
}else{
System.out.println("Folder " + fileManager.getName() + " is not moved.");
}
}
As suggested by gnomed, you can also fix your issue with the renameTo method by calling it on the original folder/file, which in this case might be 'newFolder' (confusing name) since it looks to be an actual reference to a file. Below is code with the revision.
static File newFolder = new File("C:\\template.xls");
public static void main(String[] args) {
File fileManager = new File(newFolder.getName());
try{
if(newFolder.renameTo(fileManager)){
System.out.println("Folder " + fileManager.getName() + " is moved.");
}else{
System.out.println("Folder " + fileManager.getName() + " is not moved.");
}
}catch(Exception ex){
System.out.println("Error - Folder not found!");
}
}

Categories