Java 在包含代码的jar文件旁边生成一个文件

Java 在包含代码的jar文件旁边生成一个文件,java,file,jar,Java,File,Jar,我的应用程序中有一个jar,应该在它旁边创建一个文件。因此,在文件夹中,我将有以下内容: 源代码 |_MyApplication.jar |_generatedFile.txt 简单的事我想。。。不。。我迷路了。。。我有这样一个代码: URL location = MyClass.class.getProtectionDomain().getCodeSource().getLocation(); String path = location.getFile().substrin

我的应用程序中有一个jar,应该在它旁边创建一个文件。因此,在文件夹中,我将有以下内容:

源代码
|_MyApplication.jar
|_generatedFile.txt

简单的事我想。。。不。。我迷路了。。。我有这样一个代码:

URL location = MyClass.class.getProtectionDomain().getCodeSource().getLocation();
        String path = location.getFile().substring(0, location.getFile().lastIndexOf("/MyContext"));
        File file = new File(fileName + ".txt");
        File file1 = new File(path + "/MyFileName.txt");
        File file2 = new File(path.substring(1) + "/MyFileName.txt");
我尝试了不同的组合,谷歌搜索了很多,我迷路了。。。例如,如果我得到

file1.getPath();
file2.getAbsolutePath();
以此类推,路径是正确的。。。但是文件没有生成。。。唯一的工作案例是第一个,但它位于罐子内部,我不希望这样

我还尝试使用

Paths.move(...
但这对我一点帮助都没有


有人能帮我吗?向我解释为什么上面的例子不起作用?谢谢

调用
File File=new文件(“我的路径字符串”)
只需在内存中创建一个Java
文件
对象实例。您需要在目标文件中写入一些内容。创建空文件的最简单方法是调用
file.createNewFile()

创建文件实例后是否调用了
file1.createNewFile()
。。这就解决了问题。谢谢你的解释,这对我很有帮助