【问题标题】:Move file without using renameTo()不使用 renameTo() 移动文件
【发布时间】:2013-12-15 20:05:26
【问题描述】:

在我的 Java 程序中,我想显示移动文件的进度。我使用以下 sn-p 代码来复制文件,这使我可以跟踪复制的字节并将其显示在进度条中。我想知道代码代码是否适合移动文件而不仅仅是复制它们?

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(targetFile));


            int theByte;

            while((theByte = bis.read()) != -1)
            {
                bos.write(theByte);

            }

            bis.close();
            bos.close();

【问题讨论】:

  • “我想显示移动文件的进度” - 在哪里?在控制台中,在月球上的窗口中?
  • @MadProgrammer 我确实在问题中声明我在进度条中显示它,但这不是我问题的目的。我只想知道我是否可以调整提供的代码 sn-p 来移动文件而不是复制它。
  • 我可以在控制台、Swing、AWT、JavaFX 甚至可能在 HTML 中生成进度条,如果真的推送的话,SWT 和 JNI...
  • @MadProgrammer 好的,我正在使用 Swing。但正如我所说,我认为你误解了我的问题。我只需要移动文件的代码,没有别的
  • 那么你使用的代码有什么问题?

标签: java file copy cross-platform move


【解决方案1】:

好的,所以一个“移动”操作是一个在末尾带有“删除”的副本,例如......

BufferedInputStream bis = null;
BufferedOutputStream bos = null;

try {
    bis = new BufferedInputStream(new FileInputStream(sourceFile));
    bos = new BufferedOutputStream(new FileOutputStream(targetFile));

    int theByte;

    while((theByte = bis.read()) != -1)
    {
        bos.write(theByte);
    }

    bos.close();
    bis.close();
    // You may want to verify that the file's are the same (ie the file size for example)
    if (!sourceFile.delete()) {
        throw new IOException("Failed to remove source file " + sourceFile);
    }

} catch (IOException exp) {
    exp.printStackTrace();
} finally {
    try {
        bis.close();
    } catch (Exception exp) {
    }
    try {
        bos.close();
    } catch (Exception exp) {
    }
}

【讨论】:

  • 感谢您的回答,但这肯定意味着要移动文件,您需要驱动器上可用文件的大小吗?这就是 Windows 和其他程序的工作方式吗?
  • 可以想象是的。因此,为了在同一个磁盘上移动文件,您至少需要足够的空间来制作文件的另一个副本。重命名同一磁盘上的文件时,此操作将取决于操作系统,但通常会直接更新磁盘文件表,因此文件实际上并没有(物理)在磁盘上移动,而是更新了 FT 中的索引表示新位置
  • 啊,谢谢。那很有意思。有什么地方我可以阅读更多关于这方面的内容吗?我进行了快速搜索,但实际上无法找到任何有关工作原理的技术信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-02
  • 2023-03-13
  • 1970-01-01
  • 2018-06-30
  • 1970-01-01
  • 1970-01-01
  • 2011-03-30
相关资源
最近更新 更多