0

Hi I have been working on a project in java 1.7 and have come across a problem. I am populating some arrays from text files which are stored in the project in a resources folder.

The problem i'm having is that the files are not being read from them unless they are in the package even when i try setting paths and such. What I mean by this is that the text file will not work if it's in the resource folder that has been set as the source.

This is a link to a picture of my file structure within my project.

This is a link to a picture of my text file loader.

I have had a look at some other questions but all of them just explain how to read files from for example the C drive, whereas I would like to know how to read from a file bundled inside of the finished jar file.

I would really appreciate any help that I can get as i've been trying to fix this for several days with no luck.

Lazzer555
  • 1
  • 1
  • 3

3 Answers3

2

You can use ClassLoader class to access files in the resouces folder as below:

 public static String[] load(String path){
     ClassLoader classLoader = ResourceLoader.class.getClassLoader();
     File file = new File(classLoader.getResource(path).getFile());
     List<String> lines = null;
     try {
         lines = Files.readAllLines(file.toPath());
    } catch (IOException e) {
        e.printStackTrace();
    }
     return  lines.toArray(new String[lines.size()]);
}

you can also use Files.readAllLines to read the text file into the List

have a look at this tutorial

Hope this can help.

Mario Cairone
  • 1,071
  • 7
  • 11
0

First off, to read from a jar, you would be better off with forms of methods that use the URL instead of File when there is a choice. The file system of an operating system generally can't look inside of a jar file.

Some instructions on addressing can be found in the api for Class.

The address will attempt to use the same file location as the class on which you use as the base class. In your case this is ResourceLoader, which is in the package GameFolder.

To get up a level, you use "..", so you might try the get the URL via "../src/resources/" + path. I didn't test this though, so it might need further tweaking to become a correct answer. But maybe the concepts presented will help get you to your answer.

Phil Freihofner
  • 7,645
  • 1
  • 20
  • 41
0

Once you said you already looked about how to read a file from resources I'll skip this explanation and just paste the mais thread about it here.

You said also about examples which points to C drive. Once I believe you are using it for professional projects (or at least one which have a better architecture in general) I would recommend take a look how Maven and Gradle configure your resource path (both main and test): Maven and Gradle

Community
  • 1
  • 1
Eduardo Meneses
  • 504
  • 3
  • 18