如何移动java指定文件夹中的文件?

How to move the file in specified folder in java?

这是我的代码,我想创建方法,它接受文件并将其移动到我指定文件夹的电脑中。我只是将现有的文本文件复制到另一个文本文件,但我想移动到指定的文件夹中,而不是复制。如何解决这个问题?

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();
            }
        }

您可以简单地使用 Files.movehttps://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#move(java.nio.file.Path,%20java.nio.file.Path,%20java.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);