java - 如何将 jar 文件移动到 StartUp 文件夹 - Java
问题描述
我尝试 text and jar file
使用以下代码移动到 StartUp 文件夹:
File m = new File("C:\\Users\\danyb\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\lol.txt");//startup the text file
File m2 = new File("Arma3.jar");//where the first file
File m3 = new File("C:\\Users\\danyb\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\Arma3.jar");//startup the jar file
if( !m.exists()&& !m3.exists()){
m.createNewFile();
System.out.println("a");
m2.renameTo(m3);
System.out.println("a");
FileWriter fr = new FileWriter("C:\\Users\\danyb\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\lol.txt");
BufferedWriter br = new BufferedWriter(fr);
br.write("lol");
br.close();
return;
}
我们对此进行了测试,结果是:“lol.txt”文件已创建,但 Arma3.jar 文件没有移动到文件夹,但m2.renameTo(m3);
执行后的代码但 Arma3.jar 没有移动 为什么?
解决方案
public boolean renameTo(File dest)
Renames the file denoted by this abstract pathname.
Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.
Note that the Files class defines the move method to move or rename a file in a platform independent manner.
换句话说:
- 方法
File.renameTo(File)
可能会失败并返回 false - 您应该始终检查它并通过例如抛出异常或重试操作来处理这种情况。确定实际出错的唯一方法是使用调试器,但即便如此,您最终也可能会遇到调试器无法进入的本机方法。 - 方法
File.renameTo(File)
依赖于平台,这意味着它在不同操作系统上的工作方式不同。由于使用 Java 的全部意义在于生成能够在多个系统上正确运行的应用程序,因此最好使用与平台无关的Files.move(Path, Path, CopyOptions)
(参见文档)来移动文件。
推荐阅读
- python - pygame在屏幕上显示变量不起作用
- batch-file - 如何修复用于检查已安装证书的脚本
- knockout.js - 向 SurveyJS 添加编辑器选项卡 - 无法绑定到模型
- android - 如何注册 Android ContentObserver 进行持续监控?
- wildfly - Wildfly:http访问日志IP匿名器
- api - 如何在 react-native 中渲染 JSON 对象
- python - 向 PDF 报告添加多个事件
- laravel - 使用 lsapp.test (httpd-vhosts + .hosts) 时,我的 Laravel 项目将打开主页
- octobercms - 如何在前端闪烁消息?
- azure - 在 Microsoft LUIS 平台中,我可以创建的应用数量是否有限制?