从jar创建磁盘上的文件

时间:2015-03-28 16:59:37

标签: java file jar

我的问题是每当我从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运行时只创建一个文件时,是否有任何理由可以正常工作?

0 个答案:

没有答案
相关问题