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);