将.docx文件从一个目录复制到另一个目录

时间:2020-12-21 15:03:56

So I was wondering if anyone knew how, or could point me in the direction of some samples that did this in Java? I've tried Googling it, but the examples I find are mostly related to text files.

所以我想知道是否有人知道如何,或者可以指向一些在Java中这样做的样本的方向?我试过谷歌搜索它,但我发现的例子主要与文本文件有关。

For example, with this code:

例如,使用此代码:

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

It would not work for a .docx file I don't think, right?

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

So any ideas?

那么任何想法?

Thanks in advance for any help that's offered.

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

2 个解决方案

#1


2  

I would use the java.nio package:

我会使用java.nio包:

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

However both methods should work regardless of the file type of the File since they're working with just the bytes. Just go ahead give it a go.

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

#2


0  

Copying it character by character (8-bits) works fine.

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

#1


2  

I would use the java.nio package:

我会使用java.nio包:

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

However both methods should work regardless of the file type of the File since they're working with just the bytes. Just go ahead give it a go.

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

#2


0  

Copying it character by character (8-bits) works fine.

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