java通过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;
首先我得到了罐子的路径:
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) 个答案