本例以Windows, JDK1.7 为基础,来演示对文件的拷贝重命名。
采用FileInputStream 以byte缓存的方式读取文件,同时使用FileOutputStream来新文件的写入。
演示代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.devnp.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileCopy {

public static void main(String[] args) {
// TODO Auto-generated method stub
copy();
}

/**
* Use FileInputStream read file and FileOutputStream write file
*/
public static void copy(){
InputStream inStream = null;
OutputStream outStream = null;

try{

File afile =new File("D:\\Person-Test\\1.txt");
File bfile =new File("D:\\Person-Test\\2.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();

System.out.println("File is copied successful!");

}catch(IOException e){
e.printStackTrace();
}
}

}