简体   繁体   English

在当前 .jar 文件夹中创建一个新文件

[英]Create a new file in current .jar folder

I am trying to create a new file in the directory where the .jar file is located.我正在尝试在 .jar 文件所在的目录中创建一个新文件。

public static void main(String[] args) throws IOException {
    BufferedWriter br = new BufferedWriter(new FileWriter("./filename.txt"));
    br.write("abcdefg");
    br.close();
}

This is my code but it gives me error that the file/directory does not exist.这是我的代码,但它给了我文件/目录不存在的错误。 But when creating a file like this within my IDE, it just creates a new file.但是在我的 IDE 中创建这样的文件时,它只会创建一个新文件。

All you should need is this code below and it should work.您所需要的只是下面的这段代码,它应该可以工作。 I tested it both from my IDE and from a compiled JAR file.我从我的 IDE 和编译的 JAR 文件中测试了它。

public static void main(String[] args) {
    try {
        BufferedWriter writer = new BufferedWriter(new FileWriter("Test.txt"));
        writer.write("This is a test");
        writer.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM