将文件保存到特定路径(Java)

时间:2014-09-15 21:07:34

标签: java file path save store

当我以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();
            }
        }

    }
  }     
}

1 个答案:

答案 0 :(得分:0)

由于您使用的文件名没有路径,因此您创建的文件以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