【问题标题】:Saving file to certain path (Java)将文件保存到特定路径(Java)
【发布时间】:2014-11-09 12:04:55
【问题描述】:

当我将它作为 jar 运行时,会在桌面上创建这个 .properties 文件。为了保持清洁,如何设置路径以将此文件保存在其他位置,例如文件夹?甚至是罐子本身,但我无法让它发挥作用。我打算把它交给某人,并且不希望他们的桌面在 .properties 文件中杂乱无章..

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

public class DataFile {
public static void main(String[] args) {

    Properties prop = new Properties();
    OutputStream output = null;

    try {

        output = new FileOutputStream("config.properties");

        prop.setProperty("prop1", "000");
        prop.setProperty("prop2", "000");
        prop.setProperty("prop3", "000");

        prop.store(output, null);

    } catch (IOException io) {
        io.printStackTrace();
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
  }     
}

【问题讨论】:

  • 它是干什么用的?也许Preferences API 会更合适?
  • 属性文件?我只是用它来存储用户输入的一些信息,这样下次程序运行时,这些信息就不会被删除。
  • 您有两个选择,更改启动程序的链接的“开始”引用或指定绝对路径引用

标签: java file path save store


【解决方案1】:

由于您使用的文件名没有路径,因此您创建的文件以 CWD 结尾。那是进程从操作系统继承的当前工作目录。 也就是说,您从 Desktop 目录执行 jar 文件,任何使用相对路径的文件都将在 Desktop 或其任何子目录中结束。

要控制文件的绝对位置,您必须使用绝对路径。 绝对路径总是以斜杠“/”开头。

绝对路径:

/etc/config.properties

相对路径:

sub_dir/config.properties

最简单的方法是将一些路径硬编码到文件路径字符串中。

output = new FileOutputStream("/etc/config.properties");

您当然可以在属性中设置路径,您可以使用命令行传递该路径,而不是对其进行硬编码。您将路径名和文件名连接在一起。

String path = "/etc";
String full_path = "/etc" + "/" + "config.properties";
output = new FileOutputStream(full_path);

请注意,java 中的 windows 路径使用正斜杠而不是反斜杠。 检查此以获取更多详细信息 file path Windows format to java format

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    • 2011-04-22
    • 2012-04-29
    • 2021-07-26
    相关资源
    最近更新 更多