1.利用FileStreams:
import java.io.*;
public class ReadPic {
ReadPic() {
try {
File f = new File("C:\\Users\\Lenovo\\Pictures\\Saved Pictures\\1.jpg");
File f1 = new File("C:\\Users\\Lenovo\\Pictures\\Saved Pictures\\copy1.jpg");
FileInputStream inFile = new FileInputStream(f);
BufferedInputStream inB = new BufferedInputStream(inFile);
FileOutputStream outFile = new FileOutputStream(f1);
BufferedOutputStream outB = new BufferedOutputStream(outFile);
byte b[] = new byte[(int) f.length()];
while (inB.read(b) != -1) {
outB.write(b);
}
outB.flush();
inB.close();
outB.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
new ReadPic();
}
}
2.利用 FileChannel
import java.io.*;
import java.nio.channels.FileChannel;
public class FileChannelTest {
public static void main(String args[]) throws IOException {
File source=new File("C:\\Users\\Lenovo\\Desktop\\1.txt");
File dest=new File("C:\\Users\\Lenovo\\Desktop\\2.txt");
FileChannel inputChannel = null;
FileChannel outputChannel = null;
try {
inputChannel = new FileInputStream(source).getChannel();
outputChannel = new FileOutputStream(dest).getChannel();
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
}catch(IOException e){
e.printStackTrace();
} finally {
inputChannel.close();
outputChannel.close();
}
}
}
利用Java7Files
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
public class copyFileUsingJava7FilesTest {
static void copyFileUsingJava7Files(File source, File dest)throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
public static void main(String args[]) throws IOException {
File source=new File("C:\\Users\\Lenovo\\Desktop\\1.txt");
File dest=new File("C:\\Users\\Lenovo\\Desktop\\2.txt");
copyFileUsingJava7Files(source, dest);
}
}