Java基础之读文件——使用通道复制文件(FileBackup)

摘要:
控制台程序除了使用Files类中的copy()方法复制文件外,还可以使用FileChannel对象复制文件。连接到输入文件的FileChannel对象可以直接将数据传输到连接到输出文件的FileChannel对象,而不涉及显式缓冲区。此示例用于复制命令行参数设置文件。该文件将复制到与原始目录中创建的文件类似的备份文件中。通过多次在原始文件名后附加“_backup”,新文件的名称是唯一的。

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

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

 1 import static java.nio.file.StandardOpenOption.*;
 2 import java.nio.file.*;
 3 import java.nio.channels.*;
 4 import java.io.IOException;
 5 import java.util.EnumSet;
 6 
 7 public class FileBackup {
 8   public static void main(String[] args) {
 9     if(args.length==0) {
10       System.out.println("No file to copy. Application usage is:
" + "java -classpath . FileCopy "filepath"" );
11       System.exit(1);
12     }
13     Path fromFile = Paths.get(args[0]);
14     fromFile.toAbsolutePath();
15 
16     if(Files.notExists(fromFile)) {
17       System.out.printf("File to copy, %s, does not exist.", fromFile);
18       System.exit(1);
19     }
20 
21     Path toFile = createBackupFilePath(fromFile);
22     try (FileChannel inCh = (FileChannel)(Files.newByteChannel(fromFile));
23           WritableByteChannel outCh = Files.newByteChannel( toFile, EnumSet.of(WRITE,CREATE_NEW))){
24       int bytesWritten = 0;
25       long byteCount = inCh.size();
26       while(bytesWritten < byteCount) {
27         bytesWritten += inCh.transferTo(bytesWritten, byteCount-bytesWritten, outCh);
28       }
29 
30       System.out.printf("File copy complete. %d bytes copied to %s%n", byteCount, toFile);
31     } catch(IOException e) {
32       e.printStackTrace();
33     }
34   }
35 
36   // Method to create a unique backup Path object under MS Windows
37   public static Path createBackupFilePath(Path file) {
38      Path parent = file.getParent();
39      String name = file.getFileName().toString();                      // Get the file name
40      int period = name.indexOf('.');                                   // Find the extension separator
41      if(period == -1) {                                                // If there isn't one
42        period = name.length();                                         // set it to the end of the string
43      }
44      String nameAdd = "_backup";                                       // String to be appended
45 
46      // Create a Path object that is a unique
47       Path backup = parent.resolve(
48                 name.substring(0,period) + nameAdd + name.substring(period));
49      while(Files.exists(backup)) {                                     // If the path already exists...
50         name = backup.getFileName().toString();                        // Get the current file name
51         backup = parent.resolve(name.substring(0,period) +             // add _backup
52                                 nameAdd + name.substring(period));
53        period += nameAdd.length();                                     // Increment separator index
54      }
55      return backup;
56   }
57 }

免责声明:文章转载自《Java基础之读文件——使用通道复制文件(FileBackup)》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇C# linq根据属性分组,并累加计算MUI 学习---页面跳转;页面传参;接口数据请求;页面数据绑定;构建点击事件;回调刷新;数据列表支持从右向左滑动触发删除;拨打电话下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

随便看看

【原生】CocosCreator Android和游戏的通讯 (Java和TS互相调用、传递JSON数据、监听返回键)

Cocos版本:2.4.4参考:Cocos文档-Java原生反射机制Cocos文档-JSB使用指南-在Cocos中调用Android方法2在Android中调用Cocos方法3传输JSON数据4倾听返回键5 Cocos和Android相互调用时遇到的问题,TypeScript方法可以在Java中调用,Java方法可以在TypeScript中调用。在Cocos...

安装samba服务器实现Linux mint和Windows共享文件

安装samba服务器以实现Linuxmint和Windows共享文件。在Linuxmint普通用户下执行命令:sudoapt-geinstallsamba、installsamba和打开smb。conf配置文件,并执行命令gedit/etc/samba/smb-Coff,如果您想安装gedit(sudoapt-geinstallgedit),还可以使用Lin...

C# Winform Treeview控件

WinformTreeview控件目录手动添加节点。丰富节点数据并清除所有节点信息。选择指定的节点。函数GetAllTreeNodeWinformTreeview控件手动添加节点//在根节点下添加根节点和子节点TreeNodeCollectionRoot=treeView1.Nodes;TreeNodecurNode=根。添加(“良好”);curN(电流)...

springMVC使用map接收入参 + mybatis使用map 传入查询参数

测试示例:控制器层使用映射来接收请求参数。从Debug中可以看到,请求中的参数值都是字符串形式。如果接收参数的映射直接传输到服务,mybatis将在接收参数时报告错误。因此,您需要首先对请求中的参数1packageorg.slsale进行预处理。测验23导入java.util。日期4导入java.util。HashMap;5导入java.ut...

js 浏览器窗口 刷新、关闭事件

当前页面不会直接关闭,可以点击确定按钮关闭或刷新,也可以取消关闭或刷新。...

Sublime Text 格式化JSON-pretty json

输入prettyjson回车,稍等片刻即可完成安装。...