Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (495)
Games in Android Showcase (114)
games submitted by our members
Games in WIP (563)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Having an issue loading text files  (Read 984 times)
0 Members and 1 Guest are viewing this topic.
Offline cubemaster21
« Posted 2013-08-15 02:48:43 »

I'm currently having an issue where my files will load fine with eclipse, however, they won't load when the jar is exported and run. Here is the code that is giving me trouble.
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
   private static void loadFirstNamesMale(){
      try{
         URL url = (Assets.class.getResource("/firstNamesMale.src")); // This is apparently returning as null.
        BufferedReader reader = new BufferedReader(new FileReader(new File(url.getFile())));
         String line = "";
         while((line = reader.readLine()) != null){
            firstNameMale.add(line);
         }
         System.out.println("Loaded: firstNamesMale.src");
      }catch(Exception e){
         e.printStackTrace();
      }
   }

I can't seem to find the problem. Any help is appreciated.

Check out my game, Viking Supermarket Smash
http://www.java-gaming.org/topics/iconified/28984/view.html
Offline SHC
« Reply #1 - Posted 2013-08-15 02:59:54 »

In Eclipse, I recommend not to use class folders. They can have export issues when improperly configured. The easy way is to use a
package


  • First make a package called
    res
  • Then drag all your resources from explorer to the package.
  • Now you can use this code to get an
    InputStream

1  
2  
3  
4  
public InputStream getInputStream(String name)
{
    return getClass().getClassLoader().getResourceAsStream("res/" + name);
}

This simply works. Make sure you call it with only the file name but not the resource folder.

Offline SHC
« Reply #2 - Posted 2013-08-15 03:09:06 »

Yup: Found the error in your code. The error doesn't lies at getting the URL but is at using a
FileReader


Notice that you can't use
File
to represent resources which are packed in JAR files. Hence your call to
url.getFile()
returns
null


Change your code to

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
private static void loadFirstNamesMale()
{
    try
    {
       InputStream stream = Assets.class.getResourceAsStream("/firstNamesMale.src");
       BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
        String line = "";
        while ((line = reader.readLine()) != null)
        {
            firstNameMale.add(line);
        }
        System.out.println("Loaded: firstNamesMale.src");
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

Hope this helps. I still recommend to use packages to load files easily.

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline cubemaster21
« Reply #3 - Posted 2013-08-15 03:57:24 »

I did as you said in your first post and moved everything over into a package and setup the input stream getter, however, I'm still getting a null pointer when I create the BufferedReader.

Check out my game, Viking Supermarket Smash
http://www.java-gaming.org/topics/iconified/28984/view.html
Offline SHC
« Reply #4 - Posted 2013-08-15 04:06:59 »

Can you post the stack trace? The error maybe in the code itself. Try changing your construction of buffered reader to this.

1  
2  
InputStream stream = getInputStream("firstNamesMale.src");
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));

Offline cubemaster21
« Reply #5 - Posted 2013-08-15 14:04:59 »

Yet again, it works perfectly fine in Eclipse, however, it throws the null pointer when run from a jar. Here's the stack trace. I don't know what good it will do.

and here's the methods.
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
  private static void loadFirstNamesMale(){
      try{
         InputStream url = getInputStream("firstNamesMale.src");
         BufferedReader reader = new BufferedReader(new InputStreamReader(url));
         String line = "";
         while((line = reader.readLine()) != null){
            firstNameMale.add(line);
         }
         System.out.println("Loaded: firstNamesMale.src");
      }catch(Exception e){
         e.printStackTrace();
      }
   }
   private static void loadLastNames(){
      try{
         InputStream url = getInputStream("lastNames.src");
         BufferedReader reader = new BufferedReader(new InputStreamReader(url));
         String line = "";
         while((line = reader.readLine()) != null){
            lastName.add(line);
         }
         System.out.println("Loaded: lastNames.src");
      }catch(Exception e){
         e.printStackTrace();
      }
   }
   private static InputStream getInputStream(String name){
      return Assets.class.getClassLoader().getResourceAsStream("res/" + name);
   }

Check out my game, Viking Supermarket Smash
http://www.java-gaming.org/topics/iconified/28984/view.html
Offline davidc

Senior Member


Medals: 5
Projects: 2



« Reply #6 - Posted 2013-08-15 14:58:50 »

If it's working fine in Eclipse and not when running the JAR, then the files you're trying to load are not being included in the JAR file within a folder called "res". Is there something you need to do to the folder in Eclipse for this to happen?

Here's the stack trace. I don't know what good it will do.

It is a critical piece of information. The earlier you share this with people you're asking for help, the sooner issues get resolved.
Offline sirkarpfen

Junior Member


Medals: 2
Exp: 2 years



« Reply #7 - Posted 2013-08-15 15:06:56 »

It seems like your resource just cannot be found by the InputStream. You have to check if the packages are properly named. Also if you have copied SHC's code you should check, if youre resources are located in a package called res.<YourResourcePackage>:

1  
2  
3  
4  
public InputStream getInputStream(String name)
{
    return getClass().getClassLoader().getResourceAsStream("res/" + name);
}

Offline jonjava
« Reply #8 - Posted 2013-08-15 15:18:38 »

Have you added the 'res' folder to your build path?

Project -> Properties -> Java Build Path -> Source [Tab] -> Add Folder?

In that case omit the "res/" part of the name since, if you take a look at your bin folder, you will see that there is no actual res folder added into the final package. Simply use "/" + name.

You can add an additional folder under the res folder and call it "names" - in that case, you would use "/names/" + name.

Offline cubemaster21
« Reply #9 - Posted 2013-08-15 15:25:31 »

I did like SHC said and created a new package called 'res' and used explorer to move the files into there. They get exported automatically and the folder and all of the files are present in the exported JAR. When I go to the bin folder, there is a folder called res.

Check out my game, Viking Supermarket Smash
http://www.java-gaming.org/topics/iconified/28984/view.html
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline jonjava
« Reply #10 - Posted 2013-08-15 15:36:11 »

is the 'res' folder under the 'src' folder? Also package/folder - same thing.

Offline cubemaster21
« Reply #11 - Posted 2013-08-15 15:39:23 »

Yeah, this should help to clear things up.

and all the images and .src files are in 'res'

Check out my game, Viking Supermarket Smash
http://www.java-gaming.org/topics/iconified/28984/view.html
Offline jonjava
« Reply #12 - Posted 2013-08-15 15:43:53 »

Personally I would take out the res folder from under "src" and add the "res" folder to the Java Build Path (the src folder is by default already in the Java Build Path).

However, in your case it should work by simply using "/res/resourceName.src".

Also, you should use the "Reverse Domain Name Notation" http://en.wikipedia.org/wiki/Reverse_domain_name_notation in your "toasted.com" package. I.e, rename it "com.toasted".

[EDIT]: Also, I like to use the "Navigator" instead of the "Package Explorer" in Eclipse - not that it matters.

Offline SHC
« Reply #13 - Posted 2013-08-15 16:00:17 »

It's working for me. Here's my structure of eclipse with Space Invaders project.



This is my load image method.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
public static Image loadImage(String name)
{
    Image img = null;
    if (cache == null)
    {
        cache = new HashMap < String, Image > ();
    }
    if (cache.containsKey(name))
    {
        img = cache.get(name);
    }
    else
    {
        try
        {
            img = new ImageIcon(Game.class.getClassLoader().getResource(name)).getImage();
            cache.put(name, img);
        }
        catch (Exception e)
        {
            System.err.println("Error loading image : " + name + "\nFatal error. The program is exiting.");
        }
    }
    return img;
}

And I load the images lile

1  
image = loadImage("resources/alien_ship.png");

It works for me perfectly.

Offline cubemaster21
« Reply #14 - Posted 2013-08-15 16:04:06 »

@SHC
 I'm not having any trouble loading images. They load perfectly fine. However, the trouble is with InputStreams.

@jonjava
 So, I moved the 'res' folder from 'src' and put it alongside the 'src' folder. Then I added it to the build path. Images still load fine, but the .src files will not load. The problem has got to be somewhere in this line.
1  
      return Assets.class.getClassLoader().getResourceAsStream("/" + name);

As it is always returning null.

Check out my game, Viking Supermarket Smash
http://www.java-gaming.org/topics/iconified/28984/view.html
Offline jonjava
« Reply #15 - Posted 2013-08-15 16:30:58 »

Seems like you're not getting the classLoader from an instantiated object in which case the "getClassLoader()" will return null iirc. Try changing that to:

1  
 return Assets.class.getResourceAsStream("/" + name);


http://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html

Offline sirkarpfen

Junior Member


Medals: 2
Exp: 2 years



« Reply #16 - Posted 2013-08-15 16:46:43 »

Seems like you're not getting the classLoader from an instantiated object in which case the "getClassLoader()" will return null iirc. Try changing that to:

1  
 return Assets.class.getResourceAsStream("/" + name);


http://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html

The nullPointerException suggests that the InputStream is null. In the Constructor of the InputStreamReader's superclass Reader you will find this:

1  
2  
3  
if (lock == null) {
      throw new NullPointerException();
}


lock is in that case the InputStream Object created from getResourceAsStream(). This is what getResourceAsStream() returns:

1  
2  
3  
4  
5  
6  
7  
8  
public InputStream getResourceAsStream(String name) {
      URL url = getResource(name);
      try {
            return url != null ? url.openStream() : null;
      } catch (IOException e) {
            return null;
      }
}


So your URL is definetely null. This (as we all know) only happens if your path is not valid.
Offline cubemaster21
« Reply #17 - Posted 2013-08-15 16:59:59 »

Ok, so I changed it to:
1  
return Assets.class.getResourceAsStream("/" + name);

and that works fine and dandy in eclipse, but still throws a null pointer when run from a jar.

Check out my game, Viking Supermarket Smash
http://www.java-gaming.org/topics/iconified/28984/view.html
Offline jonjava
« Reply #18 - Posted 2013-08-15 17:01:54 »

Yes, indeed, sirkarpfen.

class and ClassLoader are similar and different. Take a look at this stackoverflow post:

http://stackoverflow.com/questions/6608795/what-is-the-difference-between-class-getresource-and-classloader-getresource

try with the ClassLoader without the leading dash:

1  
return Assets.class.getClassLoader().getResourceAsStream(name);

Offline cubemaster21
« Reply #19 - Posted 2013-08-15 17:11:13 »

I did as you said, and both worked perfectly in the workspace, but STILL not when i export. I double checked that the files made it into the jar as well.

Check out my game, Viking Supermarket Smash
http://www.java-gaming.org/topics/iconified/28984/view.html
Offline sirkarpfen

Junior Member


Medals: 2
Exp: 2 years



« Reply #20 - Posted 2013-08-15 17:22:05 »

Is the res folder still in the build-path? if yes, try to remove it, paste it into your source-folder again and try it with the given advices.
Offline cubemaster21
« Reply #21 - Posted 2013-08-15 18:32:25 »

Now, quick question, with the res folder in the build path, shouldn't it automatically take everything from the res folder and drop it into the bin folder?

Check out my game, Viking Supermarket Smash
http://www.java-gaming.org/topics/iconified/28984/view.html
Offline jonjava
« Reply #22 - Posted 2013-08-15 18:35:30 »

Now, quick question, with the res folder in the build path, shouldn't it automatically take everything from the res folder and drop it into the bin folder?

Yes. There's no need to put everything inside the src folder. There's a problem somewhere else. Lemme hack an example program for some "working" code.

Offline cubemaster21
« Reply #23 - Posted 2013-08-15 18:37:08 »

Now, quick question, with the res folder in the build path, shouldn't it automatically take everything from the res folder and drop it into the bin folder?

Yes. There's no need to put everything inside the src folder. There's a problem somewhere else. Lemme hack an example program for some "working" code.
Okay, i tried deleting all the images and .src files from the bin folder and when i went to run it, it didn't automatically put them back.

Check out my game, Viking Supermarket Smash
http://www.java-gaming.org/topics/iconified/28984/view.html
Offline jonjava
« Reply #24 - Posted 2013-08-15 18:47:08 »

You shouldn't ever need to touch anything inside the bin folder yourself. Try refreshing the project. Here's a test I made and it works fine for me:

http://www.java-gaming.org/user-generated-content/members/54159/testfile.jar

You can unzip the jar file to see what's inside.



source code:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
package com.heartpirates;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.swing.JFrame;
import javax.swing.JTextArea;

public class Main extends JTextArea {

   String text = "";

   public Main() {
      this.setRows(6);
   }

   public void work() throws IOException {
      InputStream is = Main.class.getClassLoader().getResourceAsStream(
            "names.src");
      BufferedReader br = new BufferedReader(new InputStreamReader(is));

      boolean running = true;
      String s = null;
      while (true) {
         s = br.readLine();
         if (s == null)
            break;
         print(s);
      }

      print("Done.");
   }

   private void print(String s) {
      text += s + "\n";
      this.setText(text);
      System.out.println(s);
   }

   public static void main(String[] args) {
      Main m = new Main();
      JFrame frame = new JFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.add(m);
      frame.pack();
      frame.setVisible(true);
     
      try {
         m.work();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Offline cubemaster21
« Reply #25 - Posted 2013-08-15 19:00:12 »

OK, I've got it now. I've got it just how you set it up, jonjava. Also, I had no idea that the string for the name was case sensitive. You people have been a huge help. Thanks so much.

Check out my game, Viking Supermarket Smash
http://www.java-gaming.org/topics/iconified/28984/view.html
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

Dwinin (23 views)
2014-09-12 09:08:26

Norakomi (56 views)
2014-09-10 13:57:51

TehJavaDev (69 views)
2014-09-10 06:39:09

Tekkerue (34 views)
2014-09-09 02:24:56

mitcheeb (56 views)
2014-09-08 06:06:29

BurntPizza (40 views)
2014-09-07 01:13:42

Longarmx (25 views)
2014-09-07 01:12:14

Longarmx (31 views)
2014-09-07 01:11:22

Longarmx (31 views)
2014-09-07 01:10:19

mitcheeb (39 views)
2014-09-04 23:08:59
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!