简体   繁体   English

无法在Netbeans项目中获取文件路径

[英]Trouble getting file path in Netbeans project

I'm making a program that uses text files. 我正在制作一个使用文本文件的程序。 I need to make it so that the program can be run from a different computer using its jar file. 我需要这样做,以便程序可以使用其jar文件从其他计算机上运行。 The problem is that I can't get it to find the right file path to the text files. 问题是我无法找到文本文件的正确文件路径。 I've tried using getResource() , but it's still not working right. 我尝试使用getResource() ,但是仍然无法正常工作。 Here's the code: 这是代码:

public class Params {

    public static void init() {

        hsChartSuited = new int[13][13];

        file = new File(Params.class.getResource("HandStrengthDataSuited.txt").getFile());

        try {
            Scanner input = new Scanner(file);
            for (int i = 0; i < hsChartSuited.length; i++) {
                for (int j = 0; j < hsChartSuited[i].length; j++) {
                    hsChartSuited[i][j] = Integer.parseInt(input.next()) - 20;
                }
            }
        } catch (FileNotFoundException e) {
            System.out.println("File not found");

        }
}

HandStrengthDataSuited.txt is a file that is in the src folder for my project. HandStrengthDataSuited.txt是我项目的src文件夹中的文件。 It's also located outside of the folder, in the project's main directory as well. 它也位于文件夹的外部,也位于项目的主目录中。 I've tried printing the absolute file path, and this is what I get: 我尝试打印绝对文件路径,这是我得到的:

/Users/MyUsername/file:/Users/MyUsername/Documents/Homework_Soph_2012/Computer%20Science/HoldEm/dist/HoldEm.jar!/holdem/HandStrengthDataSuited.txt

The file path that I need to get is 我需要获取的文件路径是

/Users/MyUsername/Documents/Homework_Soph_2012/Computer%20Science/HoldEm/holdem/HandStrengthDataSuited.txt

Does anyone know what the problem is here? 有人知道这是什么问题吗?

If your files is in src folder, 如果您的文件位于src文件夹中,

class Tools {
    public static InputStream getResourceAsStream(String resource)
        throws FileNotFoundException
         {
        String stripped = resource.startsWith("/") ? resource.substring(1) : resource;
        InputStream stream = null;
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        if (classLoader != null) {
          stream = classLoader.getResourceAsStream(stripped);
        }
        if (stream == null) {
          stream = Tools.class.getResourceAsStream(resource);
        }
        if (stream == null) {
          stream = Tools.class.getClassLoader().getResourceAsStream(stripped);
        }
        if (stream == null) {
          throw new FileNotFoundException("Resource not found: " + resource);
        }
        return stream;
    }
}

Use: 采用:

reader = new BufferedReader(new InputStreamReader(getResourceAsStream("org/paulvargas/resources/file.txt"), "UTF-8"));

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

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