【问题标题】:How to move the file in specified folder in java?如何在java中移动指定文件夹中的文件?
【发布时间】:2021-12-02 16:48:06
【问题描述】:

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

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

【问题讨论】:

标签: java file directory copy move


【解决方案1】:

您可以简单地使用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...)

将文件移动或重命名为目标文件。 默认情况下,此方法尝试将文件移动到目标文件,如果目标文件存在则失败,除非源和目标是同一个文件,在这种情况下,此方法无效。如果文件是符号链接,则移动符号链接本身,而不是链接的目标。可以调用此方法来移动一个空目录。在一些实施方式中,目录具有用于在创建目录时创建的特殊文件或链接的条目。在这样的实现中,当仅存在特殊条目时,目录被认为是空的。当调用移动非空目录时,如果不需要移动目录中的条目,则移动目录。例如,重命名同一 FileStore 上的目录通常不需要移动目录中的条目。当移动目录需要移动其条目时,此方法将失败(通过抛出 IOException)。移动文件树可能涉及复制而不是移动目录,这可以使用 copy 方法和 Files.walkFileTree 实用程序方法来完成。

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

Files.move(sourcePath, targetPath);

【讨论】:

  • 它可以工作,但是当移动它看起来像奇怪的类型格式化程序,那么如何解决这个问题?
  • 你是什么意思weird type formatter?你能说明你有哪些路径吗?
  • 它显示类型文件,而不是 .txt 或其他东西。
  • @AnarMəmmədov,你能显示目标路径吗?
  • // 路径 sourcePath = Paths.get("C:\\Users\\anar.memmedov\\Desktop\\t.txt"); // 路径 targetPath = Paths.get("C:\\Users\\anar.memmedov\\Desktop\\ko\\test"); // // Files.move(sourcePath, targetPath);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-01
  • 2018-02-10
  • 2019-07-27
  • 2018-04-26
  • 2023-03-18
  • 2011-09-15
相关资源
最近更新 更多