Home > Back-end >  How to move the file in specified folder in java?
How to move the file in specified folder in java?

Time:10-14

This is my code, which I want to create method, that accept file and move it in my pc of specified folder. I just make this copy existing file of text to another text file, but I want to move in specified folder, not copy. How to solve this problem?

public static void main(String[] args) {
            InputStream inStream = null;
            OutputStream outStream = null;
    
            try {
    
                File afile = new File("C:\\Users\\anar.memmedov\\Desktop\\test.txt");
    
                File bfile = new File("C:\\Users\\anar.memmedov\\Desktop\\ok\\test3.txt");
    
                inStream = new FileInputStream(afile);
                outStream = new FileOutputStream(bfile);
    
                byte[] buffer = new byte[1024];
    
                int length;
                //copy the file content in bytes
                while ((length = inStream.read(buffer)) > 0) {
    
                    outStream.write(buffer, 0, length);
    
                }
    
                inStream.close();
                outStream.close();
    
                //delete the original file
                afile.delete();
    
                System.out.println("File is copied successful!");
    
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

CodePudding user response:

You can simply use Files.move: https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#move(java.nio.file.Path, java.nio.file.Path, java.nio.file.CopyOption...)

Move or rename a file to a target file. By default, this method attempts to move the file to the target file, failing if the target file exists except if the source and target are the same file, in which case this method has no effect. If the file is a symbolic link then the symbolic link itself, not the target of the link, is moved. This method may be invoked to move an empty directory. In some implementations a directory has entries for special files or links that are created when the directory is created. In such implementations a directory is considered empty when only the special entries exist. When invoked to move a directory that is not empty then the directory is moved if it does not require moving the entries in the directory. For example, renaming a directory on the same FileStore will usually not require moving the entries in the directory. When moving a directory requires that its entries be moved then this method fails (by throwing an IOException). To move a file tree may involve copying rather than moving directories and this can be done using the copy method in conjunction with the Files.walkFileTree utility method.

Path sourcePath = Paths.get("sourceFile.txt");
Path targetPath = Paths.get("targetFolder\\"   sourcePath.getFileName());

Files.move(sourcePath, targetPath);
  • Related