控制台程序,除了使用Files类中使用copy()方法将文件复制外,还可以使用FileChannel对象复制文件,连接到输入文件的FileChannel对象能直接将数据传输到连接到输出文件的FileChannel对象中而不涉及显式的缓冲区。

本例用来对命令行参数设定的文件进行复制。文件被复制到一个类似在原始目录下创建的备份文件中。新文件的名称通过在原始文件名称的后面附加多次“_backup”以获得唯一文件名。

 import static java.nio.file.StandardOpenOption.*;
import java.nio.file.*;
import java.nio.channels.*;
import java.io.IOException;
import java.util.EnumSet; public class FileBackup {
public static void main(String[] args) {
if(args.length==0) {
System.out.println("No file to copy. Application usage is:\n" + "java -classpath . FileCopy \"filepath\"" );
System.exit(1);
}
Path fromFile = Paths.get(args[0]);
fromFile.toAbsolutePath(); if(Files.notExists(fromFile)) {
System.out.printf("File to copy, %s, does not exist.", fromFile);
System.exit(1);
} Path toFile = createBackupFilePath(fromFile);
try (FileChannel inCh = (FileChannel)(Files.newByteChannel(fromFile));
WritableByteChannel outCh = Files.newByteChannel( toFile, EnumSet.of(WRITE,CREATE_NEW))){
int bytesWritten = 0;
long byteCount = inCh.size();
while(bytesWritten < byteCount) {
bytesWritten += inCh.transferTo(bytesWritten, byteCount-bytesWritten, outCh);
} System.out.printf("File copy complete. %d bytes copied to %s%n", byteCount, toFile);
} catch(IOException e) {
e.printStackTrace();
}
} // Method to create a unique backup Path object under MS Windows
public static Path createBackupFilePath(Path file) {
Path parent = file.getParent();
String name = file.getFileName().toString(); // Get the file name
int period = name.indexOf('.'); // Find the extension separator
if(period == -1) { // If there isn't one
period = name.length(); // set it to the end of the string
}
String nameAdd = "_backup"; // String to be appended // Create a Path object that is a unique
Path backup = parent.resolve(
name.substring(0,period) + nameAdd + name.substring(period));
while(Files.exists(backup)) { // If the path already exists...
name = backup.getFileName().toString(); // Get the current file name
backup = parent.resolve(name.substring(0,period) + // add _backup
nameAdd + name.substring(period));
period += nameAdd.length(); // Increment separator index
}
return backup;
}
}

Java基础之读文件——使用通道复制文件(FileBackup)的更多相关文章

  1. Java使用文件通道复制文件

    两种文件通道复制文件方式的性能比较 import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IO ...

  2. Java基础之读文件——使用输入流读取二进制文件(StreamInputFromFile)

    控制台程序,读取Java基础之读文件部分(StreamOutputToFile)写入的50个fibonacci数字. import java.nio.file.*; import java.nio.* ...

  3. Java基础-IO流对象之随机访问文件(RandomAccessFile)

    Java基础-IO流对象之随机访问文件(RandomAccessFile) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.RandomAccessFile简介 此类的实例支持对 ...

  4. Java基础之读文件——使用通道读取混合数据2(ReadPrimesMixedData2)

    控制台程序,本例读取Java基础之写文件部分(PrimesToFile2)写入的Primes.txt. 方法二:设置一个任意容量的.大小合适的字节缓冲区并且使用来自文件的字节进行填充.然后整理出缓冲区 ...

  5. Java基础之读文件——使用通道读取混合数据1(ReadPrimesMixedData)

    控制台程序,本例读取Java基础之写文件部分(PrimesToFile2)写入的Primes.txt. 方法一:可以在第一个读操作中读取字符串的长度,然后再将字符串和二进制素数值读入到文本中.这种方式 ...

  6. Java基础之读文件——使用通道读二进制数据(ReadPrimes)

    控制台程序,本例读取Java基础之写文件部分(PrimesToFile)写入的primes.bin. import java.nio.file.*; import java.nio.*; import ...

  7. Java基础之读文件——从文件中读取文本(ReadAString)

    控制台程序,使用通道从缓冲区获取数据,读取Java基础之写文件(BufferStateTrace)写入的charData.txt import java.nio.file.*; import java ...

  8. Java基础之读文件——使用缓冲读取器读取文件(ReaderInputFromFile)

    控制台程序,本例读取Java基础之写文件部分(WriterOutputToFile)写入的Saying.txt. import java.io.*; import java.nio.file.*; i ...

  9. Java基础——NIO(一)通道与缓冲区

    一.概述 1.什么是NIO NIO即New IO,这个库是在JDK1.4中才引入的.NIO和IO有相同的作用和目的,但实现方式不同,NIO主要用到的是块,所以NIO的效率要比IO高很多. 在Java ...

随机推荐

  1. PHP调用java的class

    PHP调用java的class   转:http://hi.baidu.com/lei0827/blog/item/28439a4e923234ced1c86a18.html PHP调用java的cl ...

  2. php中json_decode()和json_encode()的使用方法

    php中json_decode()和json_encode()的使用方法 作者: 字体:[增加 减小] 类型:转载   json_decode对JSON格式的字符串进行编码而json_encode对变 ...

  3. 使用 PHP 限制下载速度

    使用 PHP 限制下载速度 [来源] 达内    [编辑] 达内   [时间]2012-12-12 经常遇到一个问题,那就是有人再办公室下载东西,影响大家上网.办公.同样的问题,要是出现在了服务器上面 ...

  4. SQL_NO_CACHE

    http://dev.mysql.com/doc/refman/5.7/en/query-cache-in-select.html MySQL 5.7 Reference Manual  /  ... ...

  5. Overengineering

    https://en.wikipedia.org/wiki/Overengineering Overengineering (or over-engineering) is the designing ...

  6. Raft

    http://thesecretlivesofdata.com/raft/ https://github.com/coreos/etcd   1 Introduction Consensus algo ...

  7. Oracle存储过程java 调用

    1.nest表组合成结果集,然后以游标变量的形式返回 --创建类型 create or replace package mytest is -- Author  : ADMINISTRATOR  -- ...

  8. LogNet4学习笔记

    LogNet是一套开源的程序日志记录系统,经过配置后可以自动抓取程序中的错误.异常信息,并写入磁盘,也可以在异常发生时执行其他指定的操作,比如:通知某人右键.写入数据库等. 这里写个AspNet应用L ...

  9. //四舍五入//得到倒序//比较字符串//拦截时间,实现超时锁屏//判断是否越狱//配置PodFile//Storyboard中跳转操作//处理不可逆的push界面操作

    //处理不可逆的push界面操作 VerifyRealNameViewController *verifyRealNameCtrl = [VerifyRealNameViewController vi ...

  10. Bluetooth Low Energy介绍

    目录 1. 介绍 2. 协议栈 3. 实现方案 3.1 硬件实现方案 3.2 软件实现方案 1. 介绍 Bluetooth low energy,也称BLE(低功耗蓝牙),在4.0规范中提出 BLE分 ...