Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从jar在磁盘上创建文件_Java_File_Jar - Fatal编程技术网

Java 从jar在磁盘上创建文件

Java 从jar在磁盘上创建文件,java,file,jar,Java,File,Jar,我的问题是,每当我从Eclipse或IntelliJ运行我的程序时,我可以在一个特定的文件夹中创建尽可能多的文件,但当我创建一个jar时,它只创建一个文件,而不管我调用执行此操作的方法多少次。 详细地说,程序的一个特性允许用户在执行jar的文件夹中创建一个文件。这是通过包含静态字段和方法的类完成的。 类中的字段包括: private static StringBuilder sb = new StringBuilder(); private static Formatter formatter

我的问题是,每当我从Eclipse或IntelliJ运行我的程序时,我可以在一个特定的文件夹中创建尽可能多的文件,但当我创建一个jar时,它只创建一个文件,而不管我调用执行此操作的方法多少次。 详细地说,程序的一个特性允许用户在执行jar的文件夹中创建一个文件。这是通过包含静态字段和方法的类完成的。 类中的字段包括:

private static StringBuilder sb = new StringBuilder();
private static Formatter formatter = new Formatter(sb);
private static BufferedWriter bw;
private static String filesFolderPath;
首先,我得到了jar的路径:

private static String getJarPath() throws UnsupportedEncodingException
{
    URL url = PrintHelper.class.getProtectionDomain().getCodeSource().getLocation();
    String jarPath = URLDecoder.decode(url.getFile(), "UTF-8");
    String path = new File(jarPath).getParentFile().getPath();
    return path;
}  
然后,我设置了要将文件放入的文件夹的路径,并通过类中的静态块创建该文件夹,以便在首次使用该类时,此代码仅执行一次:

 static
 {
    try
    {   
        String dirPath = getJarPath();                 
        String fileSeparator = System.getProperty("file.separator");
        filesFolderPath = dirPath + fileSeparator + "files" + fileSeparator;

        File file = new File(filesFolderPath);
        file.mkdir();
    } catch (UnsupportedEncodingException e)
    {
        e.printStackTrace();
    }
}  
最后。每次用户希望创建文件时,都会调用此方法:

   public static void print(String filename) throws IOException, FileNotFoundException
    {
        File file = new File(filesFolderPath, getFileName(filename));
        bw = new BufferedWriter(new FileWriter(file));
        //writing with the buffered writer
        bw.close();
    }

当从IDE运行时,有什么理由让它按我所希望的那样工作,当从jar运行时,只创建一个文件

记录或打印每种情况下的路径值,以查看差异。顺便说一句,我怀疑你是否真的想使用.class.getProtectionDomain.getCodeSource.getLocation,但是由于你没有解释你想做什么或者你想把文件放在哪里,我们再也帮不了你了。我只想创建一个jar所在的文件夹并把文件放在那里。当我第一次尝试创建一个文件时,它就工作了,但是它没有工作,但是我会按照你的建议去做。另外,应该创建文件的文件夹的路径没有按预期更改。它从一开始就存储在私有静态字符串filefolderpath中;领域