Move one folder from one place to another one - java

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

Related

Deleting specified file

I'm trying to delete files but it isn't working or I'm missing something.
Here is a little test I'm doing:
private void deleteFromDir(String filename) {
String path = "./test/pacientes/" + filename + ".tds";
File f = new File(path);
System.out.println("Abs path " + f.getAbsolutePath());
System.out.println("Exist " + f.exists());
System.out.println("Filename " + f.getName());
System.out.println("Delete " + f.delete());
}
And the system prints:
Abs path C:\Users\XXXX\Documents\PAI\TSoft.\test\pacientes\John Smith.tds
Exist true
Filename John Smith.tds
Delete false
And of course isn't deleting the file, why? How can I make it work?
Perhaps, you do not have the permission to delete this file. You can use the Files.delete() method, which throws an IOException, in case something goes wrong, to see what the real problem is.

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.

Can't delete file after being renamed (file is opened)

I am using icefaces to upload files to relative path in my web app (mywebapp/audio), then after the file is getting uploaded I rename it to save its extension as follows:
public static File changeExtToWav(FileInfo fileInfo,
StringBuffer originalFileName) {
log.debug("changeExtToWav");
int mid = fileInfo.getFile().getName().lastIndexOf(".");
String fileName = fileInfo.getFile().getName().substring(0, mid);
originalFileName.append(fileName);
log.debug("originalFileName: " + originalFileName);
String newFileName = fileName + "_" + new Date().getTime() + "."
+ "wav";
File newFile = new File(fileInfo.getFile().getParent() + "/"
+ newFileName);
log.debug("newFileName: " + newFile.getName());
fileInfo.getFile().renameTo(newFile);
return newFile;
}
after the file is getting uploaded, sometimes I want to delete it from UI button as follows:
try {
File fileToDelete = new File(filePath); // correct file path
log.debug("file exists: " + fileToDelete.exists()); // true
fileToDelete.delete();
} catch (Exception e) {
e.printStackTrace();
}
the file path is correct, and I get no exceptions, but the file is not deleted (I am using java 6 btw).
please advise how to fix this issue.
UPDATE: using the following useful method, I can get that the file is opened, any ideas how to close it ?
public String getReasonForFileDeletionFailureInPlainEnglish(File file) {
try {
if (!file.exists())
return "It doesn't exist in the first place.";
else if (file.isDirectory() && file.list().length > 0)
return "It's a directory and it's not empty.";
else
return "Somebody else has it open, we don't have write permissions, or somebody stole my disk.";
} catch (SecurityException e) {
return "We're sandboxed and don't have filesystem access.";
}
}
Well if the file is open, then there is two solutions :
You have a stream in your program open on this file. Note that afaik it's a problem on Windows, with Unix I can delete a File even if a stream is opened on it.
You have an other process using this file. So in this case you can't do anything from Java.
In the log it tells also that it can be a permission problem, are you sure you have enough privileges?
You can also use Files#delete(Path path) (jdk7) to have more details about the issue.

Acces denied - obtain properties of file?

I'm running a program to list info of all files stored in folder.
I want to obtain properties of a file (the most important for me is file size, but i would like to get also other properties, like date of modification, etc.).
My problem is when I get to the file which is actually used by another program, I can't get BasicFileAtrributtes of file. I've tried to use File, URL, RandomFileAcces, but all of these requiese to open a file, and throw Exception like:
java.io.FileNotFoundException: C:\pagefile.sys (Access is denied)
Is there any option in java to obtain this properties? I prefer not to use any extra libraries, to keep small size of the application.
App is based on java JRE7.
I'm using java.nio.file.SimpleFileVisitor to visit all the files.
Here is fragment of my code, where I got the error:
#Override
public FileVisitResult visitFileFailed(Path file, IOException exc){
FileInfo temp=new FileInfo(new FileInfo().repairName(file.toString()));
temp.isLeaf=true;
temp.fName=temp.fName.replace(strIn, "");
File fis=null;
try {
fis=new File(file.toAbsolutePath().toString());
if(fis.exists())
System.out.println("exists");
if(fis.isFile())
System.out.println("isFile");
System.out.println(file.toAbsolutePath().toString());
temp.fSize=new BigInteger(new Long(fis.length()).toString());
} catch(Exception e){
e.printStackTrace();
}
node.add(temp, true);
FileListCreator.jProgressBar.setValue(++count);
return CONTINUE;
}
This works just fine for me:
File temp = new File("c:\\pagefile.sys");
System.err.println(temp.length());
System.err.println(temp.lastModified());
If the method java.io.File.exists() returns false, and the file C:\pagefile.sys exists in your file system, you specified the incorrect file path then.
The following code works on my machine:
package q10025482;
import java.io.File;
public class TestFile {
public static void main(String[] args) {
String fileName = "C:/System Volume Information";//"C:/pagefile.sys"
File file = new File(fileName);
System.out.println("\nFile " + file.getAbsolutePath() + " info:");
System.out.println("Exists: " + file.exists());
System.out.println("Is file: " + file.isFile());
System.out.println("Is dir: " + file.isDirectory());
System.out.println("Length: " + file.length());
System.out.println();
}
}
Here is the result output:
File C:\System Volume Information info:
Exists: true
Is file: false
Is dir: true
Length: 24576

Problem with creating a directory in Java

I am trying to create a directory in Java. I think I have provided correctly all necessary things so that I make the directory, but it is not created. You can see from my code below and the corresponding output that every element from which I compose the path of the new directory should be correct and valid.
It seems, however, that tDir.mkdir(); is not doing anything, and therefore the success variable is always false. I cannot understand why. Thank you in advance.
System.out.println("experimentDir: " + experimentDir);
System.out.println("item.getName(): " + item.getName());
System.out.println("dirName: " + dirName);
String tDirStr = experimentDir + "/" + item.getName() + "All/"
+ dirName + "DataAll";
System.out.println("tDirStr: " + tDirStr);
File tDir = new File(tDirStr);
if (tDir.exists()) {
System.out.println("EXISTS!!!");
} else {
boolean success = tDir.mkdir();
if(success) {
System.out.println("Dir created");
} else {
System.out.println("No dir created!");
}
Output:
experimentDir: /home/Documents/datasets/test-experiments
item.getName(): PosNegReviews
dirName: test
tDirStr: /home/Documents/datasets/test-experiments/PosNegReviewsAll/testDataAll
No dir created!
If you want to create multiple (nested) directories you should use mkdirs() (note the s).
you may be needing to create any parent directory that dont exist. try File.mkdirs().
public class Test1{
public static void main(String[] args)
{
String path="c:\\dir1\\dir2\\dir3\\dir4";
File dir=new File(path);
if(!dir.exists()){
dir.mkdirs();
}
}
}
above code will create dir4 inside C:\dir1\dir2\dir3. If parent folder does not exist, then it will also create.

Categories