在jar外面读文件 [英] Reading file right outside jar

查看:92
本文介绍了在jar外面读文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在一个文件夹中有一个.jar文件,我在该文件夹中有一些输入文件。但是,程序会在主文件夹中查找该文件(多层)。我希望它显然是从它所在的文件夹中读取它但我不想明确关于我的文件夹的文件路径,因为其他人不一定会把他们的.jar文件放在同一地点。

So I have a .jar file in a folder and I have some input files in that folder. However, the program looks for the file in the home folder (several layers up). I want it obviously to read it from the folder that it's in but I don't want to be explicit about the file path to my folder because other people won't necessarily put their .jar file in the same spot.

有没有办法直接在jar文件之外读取文件?如果没有,有没有办法在没有硬编码文件路径的情况下做到这一点?

Is there a way to read a file directly outside of the jar file? If not, is there a way to do this without hard-coding the file path?

编辑:

这是代码。它只检查输入文件是否存在。

here's the code. It just checks if the input files exist.

package main;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

/**
 * Created by chris on 12/1/15.
 * Control class that will be run when the jar is run.
 */
public class run {
    public static void main(String[] args) throws Exception {
        if (!(new File("settings.txt").exists())) {
            start.run();
        }
        if (!(new File("api_key.txt").exists())) {
            alert.display("Make your api_key.txt please.");
        } else {
            gatherData.run();
        }
    }
}

编辑2:
我尝试在开头用./添加相对引用,但这也不起作用。

edit 2: I've tried adding relative references with "./" at the beginning but that doesn't work either.

推荐答案

如果你可以依赖你的.jar文件在文件系统上,你可以通过它获得它的绝对路径

If you can rely on your .jar file being on the file system, you can get the absolute path of it by

new File(run.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());

这可能导致 SecurityException 如果a SecurityManager 存在且不允许此操作。

which can result in a SecurityException if a SecurityManager is present and not allowing this.

另一种可能性是使用

(new File(System.getProperty("java.class.path"))).getAbsolutePath();

然后可以使用 getParentFile()<获取jar文件的文件夹/ code>

The folder of the jar file can then be obtained using getParentFile()

这篇关于在jar外面读文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆