JAVA IO - java中文件拷贝剪切的5种方式

JAVA IO - java中文件拷贝剪切的5种方式

//文件拷贝:将文件从一个文件夹复制到另一个文件夹
//文件剪切:将文件从当前文件夹,移动到另一个文件夹
//文件重命名:将文件在当前文件夹下面改名(也可以理解为将文件剪切为当前文件夹下面的另一个文件)
    
//一、文件拷贝
@Test
void testCopyFile1() throws IOException {
  File fromFile = new File("D:\data\test\newFile.txt");
  File toFile = new File("D:\data\test2\copyedFile.txt");

  try(InputStream inStream = new FileInputStream(fromFile);
      OutputStream outStream = new FileOutputStream(toFile);) {

    byte[] buffer = new byte[1024];

    int length;
    while ((length = inStream.read(buffer)) > 0) {
      outStream.write(buffer, 0, length);
      outStream.flush();
    }

  }
}

@Test
void testCopyFile2() throws IOException {
  Path fromFile = Paths.get("D:\data\test\newFile.txt");
  Path toFile = Paths.get("D:\data\test2\copyedFile.txt");

  Files.copy(fromFile, toFile);
}

//StandardCopyOption.REPLACE_EXISTING 来忽略文件已经存在的异常,如果存在就去覆盖掉它
//StandardCopyOption.COPY_ATTRIBUTES copy文件的属性,最近修改时间,最近访问时间等信息,不仅copy文件的内容,连文件附带的属性一并复制
//如果目标文件存在就替换它
Files.copy(fromFile, toFile, StandardCopyOption.REPLACE_EXISTING);

CopyOption[] options = { StandardCopyOption.REPLACE_EXISTING,
      StandardCopyOption.COPY_ATTRIBUTES //copy文件的属性,最近修改时间,最近访问时间等
};
Files.copy(fromFile, toFile, options);

//二、文件重命名
@Test
void testRenameFile() throws IOException {
  Path source = Paths.get("D:\data\test\newFile.txt");
  Path target = Paths.get("D:\data\test\renameFile.txt");

  //REPLACE_EXISTING文件存在就替换它
  Files.move(source, target,StandardCopyOption.REPLACE_EXISTING);
}

@Test
void testRenameFile2() throws IOException {
  Path source = Paths.get("D:\data\test\newFile.txt");

  //这种写法就更加简单,兼容性更好
  Files.move(source, source.resolveSibling("renameFile.txt"));
}

@Test
void testRenameFile3() throws IOException {

  File source = new File("D:\data\test\newFile.txt");
  boolean succeeded = source.renameTo(new File("D:\data\test\renameFile.txt"));
  System.out.println(succeeded);  //失败了false,没有异常
}

//三、文件剪切 
//文件剪切实际上仍然是Files.move,如果move的目标文件夹不存在或源文件不存在,都会抛出NoSuchFileException
@Test
void testMoveFile() throws IOException {

  Path fromFile = Paths.get("D:\data\test\newFile.txt"); //文件
  Path anotherDir = Paths.get("D:\data\test\anotherDir"); //目标文件夹

  Files.createDirectories(anotherDir);
    //resolve函数是解析anotherDir路径与参数文件名进行合并为一个新的文件路径。
  Files.move(fromFile, anotherDir.resolve(fromFile.getFileName()),
          StandardCopyOption.REPLACE_EXISTING);
}    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值