【问题标题】:Telling .jar file to make a file on the Desktop instead of within itself (java) mac告诉 .jar 文件在桌面上而不是在其自身内创建文件(java)mac
【发布时间】:2016-03-23 04:33:16
【问题描述】:

我有一个包含以下代码行的程序:

//String s = fileName;
File location = new File(s);

然后我有

//String contents = whatIWantToPrint;
OutputStream print = new FileOutputStream(location);
    print.write(contents.getBytes());
    print.close();

告诉程序将字符串内容打印到文件 s。但是,该文件出现在程序所在的文件夹中,而不是程序所在的目录中。例如,如果程序在个人桌面上,我希望它在他们的桌面上制作文件。

我在终端中使用以下行将程序制作为 jar 文件(mac):

jar -cvmf manifest.txt Generate.jar *.class

有人告诉我这样做:

String dir = System.getProperty("home.dir"+"/Desktop");
    String filePath = dir + File.separator + ss + ".txt";
    File location = new File(filePath);

但我不确定这是否会使程序在桌面上生成文件,并且它还会引发安全异常,因此无论如何它都不起作用

【问题讨论】:

    标签: java jar properties system


    【解决方案1】:

    你应该这样做:

    String s= System.getProperty("user.home");
    

    并附加路径分隔符和文件名

    String filePath = s + File.separator + "desktop" + File.separator + "myFile.txt";
    

    【讨论】:

      【解决方案2】:

      你可以试试这个

               String DEFAULT_USER_DIR = System
              .getProperty("user.home"+"/Desktop");
               File location = new File(DEFAULT_USER_DIR);
               user.dir   returns  User's current working directory
      

      在此处查看javadoc

      【讨论】:

      • 好的,所以字符串将被设置为目录,但是您显然不应该将其粘贴到 File nameOfFile = new File(s) 中,因为这只会给您一个错误,所以我应该把那个字符串进入?
      • 该异常是一个安全异常,我想我可以关闭安全性,但 1. 即使是放置字符串的正确位置和 2. 其他人的计算机不会有这个安全问题?
      猜你喜欢
      • 2016-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-07
      • 2021-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多