1、用BufferReader和BufferWriter
String fromFile = "D:/images/test.jpg";
String toFile = signid + "" + count + fromFile.substring(fromFile.lastIndexOf("."),fromFile.length());
String filePath = session.getServletContext().getRealPath("/") + "email/mailinfo/images/";
try{
BufferedReader readChar = new BufferedReader(new FileReader(fromFile));
BufferedWriter buffer=new BufferedWriter(new FileWriter(filePath + toFile));
String line = "";
while((line = readChar.readLine()) != null){
buffer.write((line + "/n").toCharArray());
System.out.println(line);
buffer.flush();
}
readChar.close();
buffer.close();
}catch(Exception e){
e.printStackTrace();
}
2、用FileInputStream和FileOutputStream
FileInputStream input = new FileInputStream(new File(fromFile));
FileOutputStream output = new FileOutputStream(
new File(filePath + toFile));
int b;
while (true) {
byte[] buffer = {};
if (input.available() < 1024) {
while ((b = input.read()) != -1) {
output.write(b);
}
break;
} else {
input.read(buffer);
output.write(buffer);
}
}
input.close();
output.close();
3、用FileChannel(要引入java.nio.channels包)
FileInputStream input = new FileInputStream(fromFile);
FileOutputStream output = new FileOutputStream(filePath + toFile);
FileChannel infileChannel = input.getChannel();
FileChannel outfileChannel = output.getChannel();
long size = infileChannel.size();
infileChannel.transferTo(0, size, (WritableByteChannel)outfileChannel);
本文介绍了三种文件复制的方法:使用BufferedReader和BufferedWriter进行字符级别的复制;利用FileInputStream和FileOutputStream进行字节级别的复制;通过FileChannel实现高效的大文件复制。

被折叠的 条评论
为什么被折叠?



