java - 从 Windows、Mac 和 Linux 上的位置检索文件

标签 java

目前,我有一个 Java 应用程序,需要从目录复制文件并将其放在桌面上。我有这个方法

public static void copyFileUsingFileStreams(File source, File dest) throws IOException {

    InputStream input = null;
    OutputStream output = null;

    try {
        input = new FileInputStream(source);
        output = new FileOutputStream(dest);
        byte[] buf = new byte[1024];
        int bytesRead;
        while ((bytesRead = input.read(buf)) > 0) { output.write(buf, 0, bytesRead); }
    } 
    finally {
        input.close();
        output.close();
    }
}

我这样调用它。

copyFileUsingFileStreams(new File("C:/Program Files (x86)/MyProgram/App_Data/Session.db"), new File(System.getProperty("user.home") + "/Desktop/Session.db"));

这在 Windows 上完美运行。但是,我希望能够在 Mac 和 Linux 计算机上执行完全相同的操作(位置为/opt/myprogram/App_Data/Session.db)。如何评估运行的计算机是 Windows 还是 Mac/Linux,以及如何相应地重构我的代码?

最佳答案

您可以使用System.getProperty获取操作系统信息,例如

String property = System.getProperty("os.name");

此外,您可以使用 Files.copy()简化您的代码(如果您想要更多控制,请使用 StandardCopyOption )。例如

Files.copy(src, Paths.get("/opt/myprogram/App_Data/Session.db"));

所以你更新后的代码看起来像这样

public static void copyFileUsingFileStreams(File source, File dest) throws IOException {
    String property = System.getProperty("os.name");

    if (property.equals("Linux")) {
        dest = Paths.get("/opt/myprogram/App_Data/Session.db").toFile();
    }               
    //add code to adjust dest for other os.
    Files.copy(source.toPath(), dest.toPath());
}

关于java - 从 Windows、Mac 和 Linux 上的位置检索文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26002932/

相关文章:

java - java应用程序是否有类似Mockito的框架(不在JUnit/测试环境下)?

java - 如何使用SpringSource Tool Suit开发Tomcat应用?

java - 使用过的 jdbc 连接似乎在泄漏,我不知道为什么

java - 我想取出JAVA中BigInteger中存储的大数的最后一位

java - 在布局之间添加阴影

java - Android自定义点击监听器内联与字段减速为什么

java - 如何从非组件类中使用 OSGI 服务

Java 验证日期条目

java.security.AccessControlException :

Java:以毫秒为单位的时间到 HTTP 格式?