赞
踩
Java IO包的File类提供了renameTo()方法,该方法可以用来移动文件。该方法的参数为一个File对象,代表目标文件的完整路径和文件名。以下是该方法的示例代码:
File sourceFile = new File("sourceFilePath"); File destFile = new File("destinationFilePath"); if(sourceFile.renameTo(destFile)){ System.out.println("File moved successfully"); }else{ System.out.println("Failed to move file"); } 用于重命名文件或者文件夹
Java NIO包的Files类提供了多个方法来移动文件。其中,Files.move()方法是最常用的方法。该方法接收三个参数:源文件路径、目标文件路径和移动选项。以下是该方法的示例代码:
Path sourcePath = Paths.get("sourceFilePath"); Path destPath = Paths.get("destinationFilePath"); Files.move(sourcePath, destPath, StandardCopyOption.REPLACE_EXISTING);
其中,StandardCopyOption.REPLACE_EXISTING选项表示如果目标文件已经存在,则覆盖原文件。
Apache Commons IO库提供了FileUtils类,该类提供了移动文件的方法。该方法接收两个参数:源文件对象和目标文件对象。以下是该方法的示例代码:
File sourceFile = new File("sourceFilePath"); File destFile = new File("destinationFilePath"); try { FileUtils.moveFile(sourceFile, destFile); } catch (IOException e) { e.printStackTrace(); }
需要注意的是,该方法还提供了其他文件操作功能,如复制文件、删除文件等。
除以上提到的方法外,我们还可以使用Java IO流来实现文件的移动。以下是传统IO流实现文件移动的示例代码:
File sourceFile = new File("sourceFilePath"); File destFile = new File("destinationFilePath"); InputStream inputStream = new FileInputStream(sourceFile); OutputStream outputStream = new FileOutputStream(destFile); byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, length); } inputStream.close(); outputStream.close(); sourceFile.delete();
需要注意的是,该方法需要手动实现文件读取和写入,并且需要手动删除源文件。这种方法比较繁琐,建议使用以上任一一种方法完成文件移动操作。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。