本人是个菜鸟,希望各位大侠给出具体的例子,谢谢大家。
------解决方案--------------------
import java.io.*;
import java.util.*;
public class CopyFile {
private String org;
private String target;
private ArrayList list;
private byte[] b = null;
private CopyFile(String org, String target) {
this.org = org;
this.target = target;
}
/* 读文件 */
private void readFile() {
File file = new File(org);
list = new ArrayList();
if (!file.exists()) {
System.out.println( "文件不存在 ");
System.exit(0);
}
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(file);
br = new BufferedReader(fr);
String tmp = null;
while((tmp = br.readLine()) != null) {
list.add(tmp);
}
br.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//写文件
private void writeFile() {
File file = new File(target);
FileWriter fw = null;
BufferedWriter bw = null;
try {
if (!file.exists()) {
file.createNewFile();
}
fw = new FileWriter(file);
bw = new BufferedWriter(fw);
for (int i = 0; i < list.size(); i ++) {
//System.out.println(String.valueOf(list.get(i)));
bw.write(String.valueOf(list.get(i)));
bw.newLine();
}
bw.flush();
bw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
)
参考下
------解决方案--------------------
我这个是用NIO作的
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class ChannelCopy {
private static final int BSIZE = 1024;
public static void main(String[] args) throws Exception {
FileChannel
in = new FileInputStream( "D:\\source.txt ").getChannel(),
out = new FileOutputStream( "D:\\target.txt ").getChannel();
ByteBuffer buffer = ByteBuffer.allocate(BSIZE);
while(in.read(buffer) != -1) {
buffer.flip(); // Prepare for writing
out.write(buffer);
buffer.clear(); // Prepare for reading
}
}
}