使用java代码复制一个本地文件
1)直接使用文件字节流的方式读取:
private static void writeFile1(String name) throws Exception {
File file = new File(name);
if (file.isFile()) {
OutputStream fos = new FileOutputStream(file + ".bak");
InputStream fis = new FileInputStream(file);
System.out.println(file.length());
byte[] buf = new byte[4096];
int len;
while ((len = fis.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fis.close();
fos.close();
}
}
2)使用带缓冲区的字节流读取:
private static void writeFile2(String name) throws Exception {
File file = new File(name);
if (file != null && file.isFile()) {
OutputStream fos = new FileOutputStream(file + ".bak");
InputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(fos);
System.out.println(file.length());
byte[] buf = new byte[4096];
int len;
while ((len = bis.read(buf)) != -1) {
bos.write(buf, 0, len);
}
bos.flush();
fis.close();
fos.close();
}
}
3)使用FileChannel
private static void nioTransferCopy(String name) throws Exception {
File file = new File(name);
if (file != null && file.isFile()) {
System.out.println(file.length());
FileChannel in = null;
FileChannel out = null;
FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = new FileInputStream(file);
outStream = new FileOutputStream(file + ".bak");
in = inStream.getChannel();
out = outStream.getChannel();
in.transferTo(0, in.size(), out);
} catch (IOException e) {
e.printStackTrace();
} finally {
in.close();
inStream.close();
out.close();
outStream.close();
}
}
}
private static void nioBufferCopy(String name) throws Exception {
File file = new File(name);
if (file != null && file.isFile()) {
System.out.println(file.length());
FileChannel in = null;
FileChannel out = null;
FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = new FileInputStream(file);
outStream = new FileOutputStream(file + ".bak");
in = inStream.getChannel();
out = outStream.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(4096);
while (in.read(buffer) != -1) {
buffer.flip();
out.write(buffer);
buffer.clear();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
in.close();
inStream.close();
out.close();
outStream.close();
}
}
}