Moving file to new location then deleting the Previous file - 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();
}

Related

Moving from one directory to another java [duplicate]

How do you move a file from one location to another? When I run my program any file created in that location automatically moves to the specified location. How do I know which file is moved?
myFile.renameTo(new File("/the/new/place/newName.file"));
File#renameTo does that (it can not only rename, but also move between directories, at least on the same file system).
Renames the file denoted by this abstract pathname.
Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.
If you need a more comprehensive solution (such as wanting to move the file between disks), look at Apache Commons FileUtils#moveFile
With Java 7 or newer you can use Files.move(from, to, CopyOption... options).
E.g.
Files.move(Paths.get("/foo.txt"), Paths.get("bar.txt"), StandardCopyOption.REPLACE_EXISTING);
See the Files documentation for more details
Java 6
public boolean moveFile(String sourcePath, String targetPath) {
File fileToMove = new File(sourcePath);
return fileToMove.renameTo(new File(targetPath));
}
Java 7 (Using NIO)
public boolean moveFile(String sourcePath, String targetPath) {
boolean fileMoved = true;
try {
Files.move(Paths.get(sourcePath), Paths.get(targetPath), StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
fileMoved = false;
e.printStackTrace();
}
return fileMoved;
}
File.renameTo from Java IO can be used to move a file in Java. Also see this SO question.
To move a file you could also use Jakarta Commons IOs FileUtils.moveFile
On error it throws an IOException, so when no exception is thrown you know that that the file was moved.
Just add the source and destination folder paths.
It will move all the files and folder from source folder to
destination folder.
File destinationFolder = new File("");
File sourceFolder = new File("");
if (!destinationFolder.exists())
{
destinationFolder.mkdirs();
}
// Check weather source exists and it is folder.
if (sourceFolder.exists() && sourceFolder.isDirectory())
{
// Get list of the files and iterate over them
File[] listOfFiles = sourceFolder.listFiles();
if (listOfFiles != null)
{
for (File child : listOfFiles )
{
// Move files to destination folder
child.renameTo(new File(destinationFolder + "\\" + child.getName()));
}
// Add if you want to delete the source folder
sourceFolder.delete();
}
}
else
{
System.out.println(sourceFolder + " Folder does not exists");
}
Files.move(source, target, REPLACE_EXISTING);
You can use the Files object
Read more about Files
You could execute an external tool for that task (like copy in windows environments) but, to keep the code portable, the general approach is to:
read the source file into memory
write the content to a file at the new location
delete the source file
File#renameTo will work as long as source and target location are on the same volume. Personally I'd avoid using it to move files to different folders.
Try this :-
boolean success = file.renameTo(new File(Destdir, file.getName()));
Wrote this method to do this very thing on my own project only with the replace file if existing logic in it.
// we use the older file i/o operations for this rather than the newer jdk7+ Files.move() operation
private boolean moveFileToDirectory(File sourceFile, String targetPath) {
File tDir = new File(targetPath);
if (tDir.exists()) {
String newFilePath = targetPath+File.separator+sourceFile.getName();
File movedFile = new File(newFilePath);
if (movedFile.exists())
movedFile.delete();
return sourceFile.renameTo(new File(newFilePath));
} else {
LOG.warn("unable to move file "+sourceFile.getName()+" to directory "+targetPath+" -> target directory does not exist");
return false;
}
}
Please try this.
private boolean filemovetoanotherfolder(String sourcefolder, String destinationfolder, String filename) {
boolean ismove = false;
InputStream inStream = null;
OutputStream outStream = null;
try {
File afile = new File(sourcefolder + filename);
File bfile = new File(destinationfolder + filename);
inStream = new FileInputStream(afile);
outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024 * 4];
int length;
// copy the file content in bytes
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
// delete the original file
afile.delete();
ismove = true;
System.out.println("File is copied successful!");
} catch (IOException e) {
e.printStackTrace();
}finally{
inStream.close();
outStream.close();
}
return ismove;
}

Iterate through a few jars

I just made a program, which iterates through a jar file, and prints out all of the qualified path names for each .class file
My code looks like the following:
public static ArrayList<String> getClassNames(String jarName) {
ArrayList<String> CorbaClasses = new ArrayList<String>();
System.out.println("Jar " + jarName );
try {
JarInputStream jarFile = new JarInputStream(new FileInputStream(
jarName));
JarEntry jarEntry;
while (true) {
jarEntry = jarFile.getNextJarEntry();
if (jarEntry == null) {
break;
}
if (jarEntry.getName().endsWith(".class")) {
System.out.println("Found "
+ jarEntry.getName().replaceAll("/", "\\.").replace(".class", ""));
CorbaClasses.add(jarEntry.getName().replaceAll("/", "\\."));
jarFile.close();
}
}
jarFile.close();
} catch (Exception e) {
e.printStackTrace();
}
return CorbaClasses;
}
What I need now is not to iterate only through one jar file, but to iterate through a bunch of folders, where in each folder there is a jar file, that I need to print out the path names of the class files.
How can i do that?
to iterate over multiple directories/subdirectories use the following code.
File path = new File("your root Directory path");
File [] files = path.listFiles();//return list of all folder plus file in root directory
for (int i = 0; i < files.length; i++){
if (files[i].isFile()){ //if it is file do something
System.out.println(files[i]);
}else {
//it is directory go inside to find jar files
//if inside also directory found make it function and call it recursively
}
}

Delete and move file to a directory in java

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 !! :)

How do I move a file from one location to another in Java?

How do you move a file from one location to another? When I run my program any file created in that location automatically moves to the specified location. How do I know which file is moved?
myFile.renameTo(new File("/the/new/place/newName.file"));
File#renameTo does that (it can not only rename, but also move between directories, at least on the same file system).
Renames the file denoted by this abstract pathname.
Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.
If you need a more comprehensive solution (such as wanting to move the file between disks), look at Apache Commons FileUtils#moveFile
With Java 7 or newer you can use Files.move(from, to, CopyOption... options).
E.g.
Files.move(Paths.get("/foo.txt"), Paths.get("bar.txt"), StandardCopyOption.REPLACE_EXISTING);
See the Files documentation for more details
Java 6
public boolean moveFile(String sourcePath, String targetPath) {
File fileToMove = new File(sourcePath);
return fileToMove.renameTo(new File(targetPath));
}
Java 7 (Using NIO)
public boolean moveFile(String sourcePath, String targetPath) {
boolean fileMoved = true;
try {
Files.move(Paths.get(sourcePath), Paths.get(targetPath), StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
fileMoved = false;
e.printStackTrace();
}
return fileMoved;
}
File.renameTo from Java IO can be used to move a file in Java. Also see this SO question.
To move a file you could also use Jakarta Commons IOs FileUtils.moveFile
On error it throws an IOException, so when no exception is thrown you know that that the file was moved.
Just add the source and destination folder paths.
It will move all the files and folder from source folder to
destination folder.
File destinationFolder = new File("");
File sourceFolder = new File("");
if (!destinationFolder.exists())
{
destinationFolder.mkdirs();
}
// Check weather source exists and it is folder.
if (sourceFolder.exists() && sourceFolder.isDirectory())
{
// Get list of the files and iterate over them
File[] listOfFiles = sourceFolder.listFiles();
if (listOfFiles != null)
{
for (File child : listOfFiles )
{
// Move files to destination folder
child.renameTo(new File(destinationFolder + "\\" + child.getName()));
}
// Add if you want to delete the source folder
sourceFolder.delete();
}
}
else
{
System.out.println(sourceFolder + " Folder does not exists");
}
Files.move(source, target, REPLACE_EXISTING);
You can use the Files object
Read more about Files
You could execute an external tool for that task (like copy in windows environments) but, to keep the code portable, the general approach is to:
read the source file into memory
write the content to a file at the new location
delete the source file
File#renameTo will work as long as source and target location are on the same volume. Personally I'd avoid using it to move files to different folders.
Try this :-
boolean success = file.renameTo(new File(Destdir, file.getName()));
Wrote this method to do this very thing on my own project only with the replace file if existing logic in it.
// we use the older file i/o operations for this rather than the newer jdk7+ Files.move() operation
private boolean moveFileToDirectory(File sourceFile, String targetPath) {
File tDir = new File(targetPath);
if (tDir.exists()) {
String newFilePath = targetPath+File.separator+sourceFile.getName();
File movedFile = new File(newFilePath);
if (movedFile.exists())
movedFile.delete();
return sourceFile.renameTo(new File(newFilePath));
} else {
LOG.warn("unable to move file "+sourceFile.getName()+" to directory "+targetPath+" -> target directory does not exist");
return false;
}
}
Please try this.
private boolean filemovetoanotherfolder(String sourcefolder, String destinationfolder, String filename) {
boolean ismove = false;
InputStream inStream = null;
OutputStream outStream = null;
try {
File afile = new File(sourcefolder + filename);
File bfile = new File(destinationfolder + filename);
inStream = new FileInputStream(afile);
outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024 * 4];
int length;
// copy the file content in bytes
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
// delete the original file
afile.delete();
ismove = true;
System.out.println("File is copied successful!");
} catch (IOException e) {
e.printStackTrace();
}finally{
inStream.close();
outStream.close();
}
return ismove;
}

Rename a file using Java

Can we rename a file say test.txt to test1.txt ?
If test1.txt exists will it rename ?
How do I rename it to the already existing test1.txt file so the new contents of test.txt are added to it for later use?
Copied from http://exampledepot.8waytrips.com/egs/java.io/RenameFile.html
// File (or directory) with old name
File file = new File("oldname");
// File (or directory) with new name
File file2 = new File("newname");
if (file2.exists())
throw new java.io.IOException("file exists");
// Rename file (or directory)
boolean success = file.renameTo(file2);
if (!success) {
// File was not successfully renamed
}
To append to the new file:
java.io.FileWriter out= new java.io.FileWriter(file2, true /*append=yes*/);
In short:
Files.move(source, source.resolveSibling("newname"));
More detail:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
The following is copied directly from http://docs.oracle.com/javase/7/docs/api/index.html:
Suppose we want to rename a file to "newname", keeping the file in the same directory:
Path source = Paths.get("path/here");
Files.move(source, source.resolveSibling("newname"));
Alternatively, suppose we want to move a file to new directory, keeping the same file name, and replacing any existing file of that name in the directory:
Path source = Paths.get("from/path");
Path newdir = Paths.get("to/path");
Files.move(source, newdir.resolve(source.getFileName()), StandardCopyOption.REPLACE_EXISTING);
You want to utilize the renameTo method on a File object.
First, create a File object to represent the destination. Check to see if that file exists. If it doesn't exist, create a new File object for the file to be moved. call the renameTo method on the file to be moved, and check the returned value from renameTo to see if the call was successful.
If you want to append the contents of one file to another, there are a number of writers available. Based on the extension, it sounds like it's plain text, so I would look at the FileWriter.
For Java 1.6 and lower, I believe the safest and cleanest API for this is Guava's Files.move.
Example:
File newFile = new File(oldFile.getParent(), "new-file-name.txt");
Files.move(oldFile.toPath(), newFile.toPath());
The first line makes sure that the location of the new file is the same directory, i.e. the parent directory of the old file.
EDIT:
I wrote this before I started using Java 7, which introduced a very similar approach. So if you're using Java 7+, you should see and upvote kr37's answer.
Renaming the file by moving it to a new name. (FileUtils is from Apache Commons IO lib)
String newFilePath = oldFile.getAbsolutePath().replace(oldFile.getName(), "") + newName;
File newFile = new File(newFilePath);
try {
FileUtils.moveFile(oldFile, newFile);
} catch (IOException e) {
e.printStackTrace();
}
This is an easy way to rename a file:
File oldfile =new File("test.txt");
File newfile =new File("test1.txt");
if(oldfile.renameTo(newfile)){
System.out.println("File renamed");
}else{
System.out.println("Sorry! the file can't be renamed");
}
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static java.nio.file.StandardCopyOption.*;
Path yourFile = Paths.get("path_to_your_file\text.txt");
Files.move(yourFile, yourFile.resolveSibling("text1.txt"));
To replace an existing file with the name "text1.txt":
Files.move(yourFile, yourFile.resolveSibling("text1.txt"),REPLACE_EXISTING);
Try This
File file=new File("Your File");
boolean renameResult = file.renameTo(new File("New Name"));
// todo: check renameResult
Note :
We should always check the renameTo return value to make sure rename file is successful because it’s platform dependent(different Operating system, different file system) and it doesn’t throw IO exception if rename fails.
Yes, you can use File.renameTo(). But remember to have the correct path while renaming it to a new file.
import java.util.Arrays;
import java.util.List;
public class FileRenameUtility {
public static void main(String[] a) {
System.out.println("FileRenameUtility");
FileRenameUtility renameUtility = new FileRenameUtility();
renameUtility.fileRename("c:/Temp");
}
private void fileRename(String folder){
File file = new File(folder);
System.out.println("Reading this "+file.toString());
if(file.isDirectory()){
File[] files = file.listFiles();
List<File> filelist = Arrays.asList(files);
filelist.forEach(f->{
if(!f.isDirectory() && f.getName().startsWith("Old")){
System.out.println(f.getAbsolutePath());
String newName = f.getAbsolutePath().replace("Old","New");
boolean isRenamed = f.renameTo(new File(newName));
if(isRenamed)
System.out.println(String.format("Renamed this file %s to %s",f.getName(),newName));
else
System.out.println(String.format("%s file is not renamed to %s",f.getName(),newName));
}
});
}
}
}
If it's just renaming the file, you can use File.renameTo().
In the case where you want to append the contents of the second file to the first, take a look at FileOutputStream with the append constructor option or The same thing for FileWriter. You'll need to read the contents of the file to append and write them out using the output stream/writer.
As far as I know, renaming a file will not append its contents to that of an existing file with the target name.
About renaming a file in Java, see the documentation for the renameTo() method in class File.
Files.move(file.toPath(), fileNew.toPath());
works, but only when you close (or autoclose) ALL used resources (InputStream, FileOutputStream etc.) I think the same situation with file.renameTo or FileUtils.moveFile.
Here is my code to rename multiple files in a folder successfully:
public static void renameAllFilesInFolder(String folderPath, String newName, String extension) {
if(newName == null || newName.equals("")) {
System.out.println("New name cannot be null or empty");
return;
}
if(extension == null || extension.equals("")) {
System.out.println("Extension cannot be null or empty");
return;
}
File dir = new File(folderPath);
int i = 1;
if (dir.isDirectory()) { // make sure it's a directory
for (final File f : dir.listFiles()) {
try {
File newfile = new File(folderPath + "\\" + newName + "_" + i + "." + extension);
if(f.renameTo(newfile)){
System.out.println("Rename succesful: " + newName + "_" + i + "." + extension);
} else {
System.out.println("Rename failed");
}
i++;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
and run it for an example:
renameAllFilesInFolder("E:\\Downloads\\Foldername", "my_avatar", "gif");
I do not like java.io.File.renameTo(...) because sometimes it does not renames the file and you do not know why! It just returns true of false. It does not thrown an exception if it fails.
On the other hand, java.nio.file.Files.move(...) is more useful as it throws an exception when it fails.
Running code is here.
private static void renameFile(File fileName) {
FileOutputStream fileOutputStream =null;
BufferedReader br = null;
FileReader fr = null;
String newFileName = "yourNewFileName"
try {
fileOutputStream = new FileOutputStream(newFileName);
fr = new FileReader(fileName);
br = new BufferedReader(fr);
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
fileOutputStream.write(("\n"+sCurrentLine).getBytes());
}
fileOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileOutputStream.close();
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

Categories