I am trying to move a file from one directory to another using renameTo() in java, however renameTo doesnt work (doesnt rename and move the file). Basically, I want to delete the file in one first with same file name, then copy a file from anoter directory to the same location where I deleted the file originally, then copy the new one with same name.
//filePath = location of original file with file name appended. ex: C:\Dir\file.txt
//tempPath = Location of file that I want to replace it to file file without the file name. ex: C:\AnotherDir
int pos = filePath.indexOf("C:\\Dir\\file.txt");
//Parse out only the path, so just C:\\Dir
String newFilePath = filePath.substring(0,pos-1);
//I want to delete the original file
File deletefile = new File(newFilePath,"file.txt");
if (deletefile.exists()) {
success = deletefile.delete();
}
//There is file already exists in the directory, but I am just appending .tmp at the end
File newFile = new File(tempPath + "file.txt" + ".tmp");
//Create original file again with same name.
File oldFile = new File(newFilePath, "file.txt");
success = oldFile.renameTo(newFile); // This doesnt work.
Can you tell me what I am doing wrong?
Thanks for your help.
You need to escape the backslashes in the string literal: "C:\\Dir\\file.txt". Or use File.separator to construct the path.
Additionally, ensure newFile's path is constructed properly:
File newFile = new File(tempPath + File.separator + "file.txt" + ".tmp");
//^^^^^^^^^^^^^^^^
as the commments in the posted code (...ex: C:\AnotherDir) indicate that tempPath has no trailing slash character.
I have moved files to the destination directory and after moving deleted those moved files from source folder, in three ways, and at last am using the 3rd approach in my project.
1st approach:
File folder = new File("SourceDirectory_Path");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
Files.move(Paths.get("SourceDirectory_Path"+listOfFiles[i].getName()), Paths.get("DestinationDerectory_Path"+listOfFiles[i].getName()));
}
System.out.println("SUCCESS");
2nd approach:
Path sourceDir = Paths.get("SourceDirectory_Path");
Path destinationDir = Paths.get("DestinationDerectory_Path");
try(DirectoryStream<Path> directoryStream = Files.newDirectoryStream(sourceDir)){
for (Path path : directoryStream) {
File d1 = sourceDir.resolve(path.getFileName()).toFile();
File d2 = destinationDir.resolve(path.getFileName()).toFile();
File oldFile = path.toFile();
if(oldFile.renameTo(d2)){
System.out.println("Moved");
}else{
System.out.println("Not Moved");
}
}
}catch (Exception e) {
e.printStackTrace();
}
3rd approach:
Path sourceDirectory= Paths.get(SOURCE_FILE_PATH);
Path destinationDirectory = Paths.get(SOURCE_FILE_MOVE_PATH);
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(sourceDirectory)) {
for (Path path : directoryStream) {
Path dpath = destinationDirectory .resolve(path.getFileName());
Files.move(path, dpath, StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException ex) {
ex.printStackTrace();
}
Happy Coding !! :)
Related
I am facing issues when trying to ignore files with.db extension placed in folder location(say (\test\folder) using below java code.The code on execution is not working as expected and the files containing .db extension isn't ignored [which is what we are looking at in our requirement].
Please advice what changes or missing points are there in the below enlisted code.
I have pasted the code snippet causing trouble and not ignoring the file of .db extension.
String mess1 = "";
String mess2 = "";
String ext = "Thumbs.db";
Boolean result = false;
try{
File folder = new File(folderPath);
System.out.println(folder);
if(folder.exists()){
File[] listOfFiles = folder.listFiles();
if(listOfFiles.length > 0){
for(int i=0;i<listOfFiles.length;i++){
String name= listOfFiles[i].toString();
if(name.equalsIgnoreCase(ext)){
out.println(name);
result = false;
}
}
}
}
File.toString() does not do what you probably expect it to do. It returns the pathname string of this abstract pathname, not the name of the file.
Try File.getName() instead.
You should use file.getName() instead of file.toString() to abtain the name of the file and not the pathname.
Then you should use name.matches() instead of name.equals() to obtain all the files that have .db extension and not only the one with the name Thumbs.db
Please try below code which will print files ending with .db extension.
String mess1 = "";
String mess2 = "";
String ext = ".db";
Boolean result = false;
try{
File folder = new File("C:/FTP/");
System.out.println(folder);
if(folder.exists()){
File[] listOfFiles = folder.listFiles();
if(listOfFiles.length > 0){
for(int i=0;i<listOfFiles.length;i++){
String name= listOfFiles[i].getName();
if(name.endsWith(ext))
{
System.out.println(name);
result = false;
}
}
}
}
}catch(Exception e) {}
I'm saving an uploaded file as below:
UploadItem item = event.getUploadItem();
File dir = new File("D:/FileUpload");
if (!dir.exists()) {
dir.mkdir();
}
File bfile = new File("D:/FileUpload" + "/" + item.getFileName());
OutputStream outStream = new FileOutputStream(bfile);
outStream.write(item.getData());
outStream.close();
But my question is when upload once file same old file in folder D:/FileUpload. In above function it will delete old file. Example first time, i upload file : test.doc (old file). Then i upload another file with same name : test.doc (new file). At folder FileUpload will has one file is test.doc (new file). I want function will process similar in window OS is : new file will be test (2).doc. How can i process it ? And all cases : D:/FileUpload have many file : test.doc, test (1).doc, test (2).doc, test (a).doc,...... I think we just check with format ....(int).doc. That new file will be :
test (3).doc (ignore test(a).doc)
Maybe you're looking for something like this? I list the files in your directory, compare the names of each to the name of your file. If the names match, increment a count. Then, when you come to create your file, include the count in its name.
UploadItem item = event.getUploadItem();
File dir = new File("D:/FileUpload");
if (!dir.exists()) {
dir.mkdir();
}
String [] files = dir.list();
int count = 0;
for(String file : files) {
if (file.startsWith(item.getFileName()) {
count++;
}
}
File bfile = new File("D:/FileUpload" + "/" + item.getFileName() + "(" + count + ")");
OutputStream outStream = new FileOutputStream(bfile);
outStream.write(item.getData());
outStream.close();
I am using the NIO libraries but I am getting a strange error when I try to move files from one directory to another.
String yearNow = new SimpleDateFormat("yyyy").format(
Calendar.getInstance().getTime());
try {
DirectoryStream<Path> curYearStream =
Files.newDirectoryStream(sourceDir, "{" + yearNow + "*}");
//Glob for current year
Path newDir = Paths.get(sourceDir + "//" + yearNow);
if (!Files.exists(newDir) || !Files.isDirectory(newDir)) {
Files.createDirectory(newDir);
//create 2014 directory if it doesn't exist
}
}
Iterate over elements that start with "2014" and move them in the new directory (newDir, which is also called 2014)
for (Path p : curYearStream) {
System.out.println(p); //it prints out exactly the files that I need to move
Files.move(p, newDir); //java.nio.file.FileAlreadyExistsException
}
I get the java.nio.file.FileAlreadyExistsException because my folder (2014) already exists. What I actually want to do is move all the files that start with "2014" INSIDE the 2014 directory.
Better not going back to java.io.File and using NIO instead:
Path sourceDir = Paths.get("c:\\source");
Path destinationDir = Paths.get("c:\\dest");
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(sourceDir)) {
for (Path path : directoryStream) {
System.out.println("copying " + path.toString());
Path d2 = destinationDir.resolve(path.getFileName());
System.out.println("destination File=" + d2);
Files.move(path, d2, REPLACE_EXISTING);
}
} catch (IOException ex) {
ex.printStackTrace();
}
Files.move is not equivalent to the mv command. It won't detect that the destination is a directory and move files into there.
You have to construct the full destination path, file by file. If you want to copy /src/a.txt to /dest/2014/, the destination path needs to be /dest/2014/a.txt.
You may want to do something like this:
File srcFile = new File("/src/a.txt");
File destDir = new File("/dest/2014");
Path src = srcFile.toPath();
Path dest = new File(destDir, srcFile.getName()).toPath(); // "/dest/2014/a.txt"
Continue with #Andrew's answer
If we use only Files.move(src, dst, StandardCopyOption.REPLACE_EXISTING); then it will delete source directory because we only provide a directory path not an absolute path of a particular file. So it will also delete a source directory when operation will be done.
Let's say source path is /opt/src which contains a csv files and destination path is /opt/dst and I want to move all files from src to dst and I'm using Files.move(src, dst, StandardCopyOption.REPLACE_EXISTING); this then it will move all the files to dst but it will delete a src directory after moving all files because we didn't provide an absolute path of a each file for src as well as dst. We should have to provide src path like /opt/src/foo.csv and dst path like /opt/dst/foo.csv then and then it will not delete a source directory.
DirectoryStream used to iterate over the entries in a directory. A directory stream allows for the convenient use of the for-each construct to iterate over a directory. So we get an absolute path for src and we use resolve method for resolving an absolute path for dst.
Please refer DirectoryStream for more information.
Try this code:
public class App
{
public void moveFromSourceToDestination(String sourceName,String destinationName)
{
File mydir = new File(sourceName);
if (mydir.isDirectory())
{
File[] myContent = mydir.listFiles();
for(int i = 0; i < myContent.length; i++)
{
File file1 = myContent[i];
file1.renameTo(new File(destinationName+file1.getName()));
}
}
}
public static void main(String [] args)
{
App app = new App();
String sourceName = "C:\\Users\\SourceFolder";
String destinationName = "C:\\Users\\DestinationFolder\\";
app.moveFromSourceToDestination(sourceName,destinationName);
}
}
Using java.io.File, its as simple as this:
File srcFile = new File(srcDir, fileName);
srcFile.renameTo(new File(destDir, "a.txt"));
I am having an input folder say c:\files\input\ that contains my list of files that I am using.
How do I use the above to create say c:\files\output\ and copy the files from the input folder to the output folder?
My c:\files\input is read from an object, say
String inputFolder = dataMap.getString("folder");// this will get c:\files\input\
You got path of folder in variable inputFolder now do as follows.
String inputFolder = dataMap.getString("folder");
File dir = new File(inputFolder);
if(dir.mkdirs()){
System.out.println("Directory created");
}else{
System.out.println("Directory Not Created");
}
You can use FileUtils from org.apache.commons.io library
FileUtils.copyDirectory(srcDir, destDir);
so in your case:
File file = new File(inputFolder);
String parentDir = file.getParentFile().getAbsolutePath();
File outputDir = new File(parentDir, "output");
if(!outputDir.exsit()) {
outputDir.mkdir();
}
FileUtils.copyDirectory(inputFolder, outputDir);
To Create the directory you can refer to the below code
File file = new File("c:\\files\\output");
if (!file.exists()) {
if (file.mkdir()) {
System.out.println("Directory is created!");
} else {
System.out.println("Failed to create directory!");
}
}
To copy files from a directory to another directory.. refer to the following link it gives a good explanation with source code examples
http://examples.javacodegeeks.com/core-java/io/file/4-ways-to-copy-file-in-java/
I want to move file from one path to another path but instead of moving it copy the file to new location.
Kindly provide any hints
Thanks in advance
MovePngToPreviewDir pngToPreviewDir = new MovePngToPreviewDir(null, "png");
File[] listOfPNGFiles = RootDir.listFiles(pngToPreviewDir);
for(File file:listOfPNGFiles){
Log.e("PNG = ",file.getAbsolutePath());
Log.e("PNG = ",file.getName());
if(previewDiagramDir == null){
Log.e("Preview Diagram Dir is NULL","Preview Diagram DIR is NULL");
}
if(file!= null && previewDiagramDir != null){
Log.e("Preview Diagram Dir",previewDiagramDir.getAbsolutePath()+"/");
if(file.renameTo(new File(previewDiagramDir, file.getName()))){
Log.e("PNG File is successfully Moved",file.getName());
}else{
Log.e("Error in Moving PNG File","Error in Moving PNG file");
}
}else{
}
If you want to copy the file to another location, you can use file.renameTo() method of File class, related to your istance object file, trying this:
file.renameTo(new File("new_directory_to_copy_file"+file.getName()));
After copying the file, you can delete it with file.delete();.
Note: The method delete() returns a boolean object, then you can check the correct file deletion with:
boolean del = file.delete();
if(del) System.out.println("File "+file.getName()+" deleted!");
else System.out.println("File "+file.getName()+"not deleted!");
About the File class API: http://download.oracle.com/javase/6/docs/api/java/io/File.html
Use file.delete() after the file is copied to another location so that it is completely moved to the new location.
I have moved files to the destination directory and after moving deleted those moved files from source folder, in three ways, and at last am using the 3rd approach in my project.
1st approach:
File folder = new File("SourceDirectory_Path");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
Files.move(Paths.get("SourceDirectory_Path"+listOfFiles[i].getName()), Paths.get("DestinationDerectory_Path"+listOfFiles[i].getName()));
}
System.out.println("SUCCESS");
2nd approach:
Path sourceDir = Paths.get("SourceDirectory_Path");
Path destinationDir = Paths.get("DestinationDerectory_Path");
try(DirectoryStream<Path> directoryStream = Files.newDirectoryStream(sourceDir)){
for (Path path : directoryStream) {
File d1 = sourceDir.resolve(path.getFileName()).toFile();
File d2 = destinationDir.resolve(path.getFileName()).toFile();
File oldFile = path.toFile();
if(oldFile.renameTo(d2)){
System.out.println("Moved");
}else{
System.out.println("Not Moved");
}
}
}catch (Exception e) {
e.printStackTrace();
}
3rd approach:
Path sourceDirectory= Paths.get(SOURCE_FILE_PATH);
Path destinationDirectory = Paths.get(SOURCE_FILE_MOVE_PATH);
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(sourceDirectory)) {
for (Path path : directoryStream) {
Path dpath = destinationDirectory .resolve(path.getFileName());
Files.move(path, dpath, StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException ex) {
ex.printStackTrace();
}