【问题标题】:Copying .docx Files From One Directory to Another将 .docx 文件从一个目录复制到另一个目录
【发布时间】:2011-10-24 07:38:27
【问题描述】:

所以我想知道是否有人知道如何,或者可以指出一些在 Java 中执行此操作的示例的方向?我试过用谷歌搜索它,但我发现的例子大多与文本文件有关。

例如,使用以下代码:

// Copies src file to dst file.
// If the dst file does not exist, it is created
void copy(File src, File dst) throws IOException {
    InputStream in = new FileInputStream(src);
    OutputStream out = new FileOutputStream(dst);

    // Transfer bytes from in to out
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    in.close();
    out.close();
}

我认为它不适用于 .docx 文件,对吧?

有什么想法吗?

提前感谢您提供的任何帮助。

【问题讨论】:

  • 你试过了吗?它应该适用于任何类型的“文件”。
  • 为什么这不适用于 .docx 文件?该代码对我来说似乎是正确的,它按字节复制文件。
  • 根据我的转换经验,我知道格式有时会发生变化。所以我只是想知道是否有人以前尝试过。
  • 为什么在发帖前不自己测试一下?
  • 诚实吗?懒惰和怀疑的结合。对不起,哈哈。

标签: java file-io directory copy docx


【解决方案1】:

使用 File.Copy 或 File.Directory,类似这样的东西

 var oldfile = "C\\folder";
 var Newfile = "C\\Newfolder";

if(File.Exsit(NewFile)){
File.Copy(oldfile, Newfile);
Message.Show("Yourmessage");
}
else{
Message.Show("If it fails");
}

我添加了 If 语句以确保它有效

【讨论】:

    【解决方案2】:

    逐个字符(8 位)复制它可以正常工作。

    void copy(File src, File dst) throws IOException {
        InputStream in = new FileInputStream(src);
        OutputStream out = new FileOutputStream(dst);
    
        int c;
        while ((c = in.read(buf)) > 0) {
            out.write(c);
        }
        in.close();
        out.close();
    }
    

    【讨论】:

      【解决方案3】:

      我会使用 java.nio 包:

      FileChannel in = new FileInputStream( src ).getChannel();
      FileChannel out = new FileOutputStream( dst ).getChannel();
      out.transferFrom( in, 0, in.size() );
      in.close();
      out.close();
      

      但是,无论File 的文件类型如何,这两种方法都应该有效,因为它们只使用字节。继续努力吧。

      【讨论】:

      • 你确定这是对的吗?我试图在我的程序中弄乱它,Eclipse 告诉我将 in 的类型从 FileInputStream 更改为 FileChannel?
      • 抱歉,这是一个错字,请将 FileInputStreamFileOutputStream 更改为 FileChannel
      猜你喜欢
      • 2012-02-15
      • 2017-11-18
      • 2013-06-01
      • 2020-06-22
      • 2014-08-12
      • 2013-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多