java 本地文件复制的方法
2013-12-17 10:59
351 查看
使用java代码复制一个本地文件
1)直接使用文件字节流的方式读取:
2)使用带缓冲区的字节流读取:
3)使用FileChannel
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(); } } }
相关文章推荐
- Java使用字节流复制文件的方法
- 如何解决本地电脑不能复制文件到远程服务器的方法
- java方法客户端下载服务器上的文件到本地
- 禁止删除、修改共享文件,防止局域网用户私自复制共享文件到本地的方法
- Java: 复制文件最快方法
- Java: 复制文件最快方法
- java调用scp,文件从本地复制到远程
- 【Java】利用文件通道的方式改进Java复制单个文件的方法
- Java读取本地json文件及相应处理方法
- Java 复制文件的高效方法
- 4 Ways to Copy File in Java -- Java 复制文件的方法
- java 本地文件复制(将文件拷贝到另一个目录)
- 将某盘的java文件复制到目标文件的方法。
- 利用xcopy命令实现本地文件复制到远程服务器的方法
- java 实现文件复制,二种方法.
- java字节流复制文件的方法
- java方法客户端下载服务器上的文件到本地
- Java 实现文件复制方法
- Java 高效复制文件方法