Java-Gaming.org    
Featured games (78)
games approved by the League of Dukes
Games in Showcase (429)
Games in Android Showcase (89)
games submitted by our members
Games in WIP (468)
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  
  IO exception catch  (Read 2854 times)
0 Members and 1 Guest are viewing this topic.
Offline westloar

Junior Member





« Posted 2012-04-19 16:55:36 »

OK, so I know I've posted ALOT in the last few days but I could really do with your help on this one.

The following code attempts to read a text file to obtain and store information about where it should put bricks(tiles) on the screen and what image it should paint them.

When run it tells me that it begins reading the file (due to a out.println) and then tells me that it has an error again due to println. I have put another println in for debugging purposes within the while loop and found that it doesn't get past the first branch, I can't see why, here's the 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  
{ 
    String imsFNm = IMAGE_DIR + fnm;
    System.out.println("Reading bricks file: " + imsFNm);

    int numStripImages = -1;
    int numBricksLines = 0;
    try {
      BufferedReader br = new BufferedReader( new FileReader(imsFNm));
      String line;
      char ch;
      while((line = br.readLine()) != null) {
        if (line.length() == 0)  // ignore a blank line
           continue;
        System.out.println("Break 1");
        if (line.startsWith("//"))   // ignore a comment line
         continue;
        ch = Character.toLowerCase( line.charAt(0) );
        if (ch == 's')  // an images strip
         numStripImages = getStripImages(line);
        else {  // a bricks map line
         if (numBricksLines > MAX_BRICKS_LINES)
            System.out.println("Max reached, skipping bricks line: " + line);
          else if (numStripImages == -1)
            System.out.println("No strip image, skipping bricks line: " + line);
          else {
            storeBricks(line, numBricksLines, numStripImages);
            numBricksLines++;
          }
        }
      }
      br.close();
    }
    catch (IOException e)
    { System.out.println("Error reading file: " + imsFNm);
      System.exit(1);
    }


The debugging println prints "break 1", but when ran it doesn't reach this branch, this is the output it produces:

1  
2  
3  
4  
Reading bricks file: Images/bricksInfo.txt
Error reading file: Images/bricksInfo.txt
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)


I know that the file paths are correct and that the code points to the right file, so I can't explain this, any help would be appreciated, thanks.
Offline 65K
« Reply #1 - Posted 2012-04-19 17:13:16 »

1  
2  
3  
4  
5  
catch (IOException e) 
 {
   System.out.println("Error reading file: " + imsFNm);
   System.exit(1);
}

Never ever swallow the given cause of an exception.
So, print e.getMessage() and see whats going on...

Offline westloar

Junior Member





« Reply #2 - Posted 2012-04-19 17:21:57 »

cheers that was a great help, in fact it turns out it can't find the file specified, although I can't understand why, here's the file structure:



bricksInfo.txt is clearly in the correct path and the println tells us the code points to it, what's going on?
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline 65K
« Reply #3 - Posted 2012-04-19 17:25:20 »

Maybe "labrat" is not your current directory when running ?

Offline westloar

Junior Member





« Reply #4 - Posted 2012-04-19 17:29:34 »

a fair point, but there are two other almost identical bits of code that deal with sound clips and images, they both use .txt files contained within the LabRat directory, so I don't think that could be the answer (they run before bricksManager and the log shows that they run successfully).

[EDIT]: In fact ImagesLoader uses a text file from "LabRat/Images", the same directory that bricksInfo.txt is stored.
Offline theagentd
« Reply #5 - Posted 2012-04-19 17:29:55 »

The path should be relative to your project's root folder. It's only relative to your class file if you use Class.getResource() if I remember correctly.

Myomyomyo.
Offline westloar

Junior Member





« Reply #6 - Posted 2012-04-19 17:35:19 »

So any idea as to why it can't find bricksInfo.txt then?
Offline sproingie

JGO Kernel


Medals: 200



« Reply #7 - Posted 2012-04-19 17:35:50 »

Load your image as a resource, not a file.  Something like this:

1  
2  
InputStream is = getClass().getClassLoader().getResourceAsStream("/labrat/Images/" + fnm);
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));


If you do want it relative to your package, replace the first line with this instead:

1  
InputStream is = getClass().getResourceAsStream("Images/" + fnm);


Oh also notice the encoding: you should always give an encoding, and that's a reason to not use FileReader, which doesn't take one.
Offline westloar

Junior Member





« Reply #8 - Posted 2012-04-19 17:42:23 »

Ok, so I put in the code you suggested and when run the log produces a NullPointerException:

1  
2  
3  
4  
Exception in thread "main" java.lang.NullPointerException
   at java.io.Reader.<init>(Reader.java:78)
   at java.io.InputStreamReader.<init>(InputStreamReader.java:97)
   at labrat.BricksManager.loadBricksFile(BricksManager.java:140)


suggesting to me that it still can't find the text file?
Offline sproingie

JGO Kernel


Medals: 200



« Reply #9 - Posted 2012-04-19 17:49:45 »

I know the answer, but I'm going to break into "teaching to fish" mode and ask you to find out what's null here.  Trust your initial instinct.  If you suspect it's still not finding the file, try doing something like URL res = getClass().getClassLoader().getResource(...) then printing res and seeing if the filename or jar path name looks right.
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline westloar

Junior Member





« Reply #10 - Posted 2012-04-19 18:07:55 »

so I println'd "res" and it returned "null"

does this mean there's an issue with my "fnm" variable?
Offline sproingie

JGO Kernel


Medals: 200



« Reply #11 - Posted 2012-04-19 18:19:25 »

It means it failed to find a resource with that name, so it's probably an issue with what was passed in, yes.  What's the full path you pass in to getResource()?  Also, is labrat at the root of your packages?  It's difficult to debug this stuff on the forum without a full file to work from (which would have a package statement and probably the value of IMAGE_DIR)
Offline westloar

Junior Member





« Reply #12 - Posted 2012-04-19 18:29:08 »

1  
2  
3  
public class BricksManager
{
  private final static String IMAGE_DIR = "Images/";


The path I put into the code to direct it to bricksInfo.txt is "Images + fnm" (fnm = bricksInfo.txt) meaning that imsFnm = Images/bricksInfo.txt

The only problem I have with your explanation is that there are two other classes that use the same method to load images, ImagesLoader, and sound clips, ClipsLoader. And they run with no issues. I don't understand why this would be any different?
Offline sproingie

JGO Kernel


Medals: 200



« Reply #13 - Posted 2012-04-19 19:05:22 »

The only problem I have with your explanation is that there are two other classes that use the same method to load images, ImagesLoader, and sound clips, ClipsLoader. And they run with no issues. I don't understand why this would be any different?

If you have a relative path, you need to use getClass().getResourceAsStream(), i.e. leave off the getClassLoader() part.  That'll load the resource relative to the location of the class doing the loading.  The classes that are working are in the 'labrat' package, whereas the class you're testing either isn't in the same package, or is using the getClassLoader() version, which is an absolute path regardless of whether it starts with a '/' or not.

I prefer to use relative paths only for default config files like properties, and absolute paths (starting with a '/') for global resources like images.  It saves a lot of confusion like the kind you're experiencing.

Offline westloar

Junior Member





« Reply #14 - Posted 2012-04-19 23:10:31 »

First of all, thankyou that has worked and now everything runs smoothly.

But for the sake of my learning and my mind, I know that bricksmanager is in the LabRat package, as is bricksInfo and the assets it refers to, so why did that make a difference?
Offline philfrei
« Reply #15 - Posted 2012-04-19 23:45:28 »

I'm jumping in kind of late, and am not following all the details. But I will venture to answer the last question:

Quote
But for the sake of my learning and my mind, I know that bricksmanager is in the LabRat package, as is bricksInfo and the assets it refers to, so why did that make a difference?

There are two methods commonly used in loading resources:
  • getResource()
  • getResourceAsStream()

Qualitatively different assets (images vs. text files vs. sounds) will require that you use the correct one of these two. You may have gotten the two methods interchanged or mixed up at some point.

Secondly, the method getClass() refers to the current class, which may not be in the base location. If this class is in a subfolder or subpackage, it would have a different location relative to your Images folder.

Those are the two main reasons that I can think of that might explain why one load worked and another didn't.

It gets more confusing (to me, anyway Smiley ) when loading resources from jar files. When I have doubts, I consult the following Java tutorial. The section "Loading Images using getResource" has examples of various scenarios:

    http://docs.oracle.com/javase/tutorial/uiswing/components/icon.html

P.S. When loading audio assets, it is better to use URLs than InputStreams (which can sometimes throw mark/reset errors).

"Greetings my friends! We are all interested in the future, for that is where you and I are going to spend the rest of our lives!" -- The Amazing Criswell
Offline westloar

Junior Member





« Reply #16 - Posted 2012-04-20 00:02:41 »

Well having taken a good hard look at all of the code, including the 2 classes that already worked I realised that the BricksManager was missing an input stream in the first place, so how was bufferedReader meant to find the file.

BUT I have learned a lot about input streams, so I can't thank sproingie enough for his patience and willing to teach me and for philfrei for the explanation and tutorial link Cheesy

Who said the internet is full of trolls Tongue (or maybe java developers actually have souls!) ?
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.

theagentd (6 views)
2014-04-24 23:00:44

xsi3rr4x (83 views)
2014-04-15 18:08:23

BurntPizza (75 views)
2014-04-15 03:46:01

UprightPath (86 views)
2014-04-14 17:39:50

UprightPath (69 views)
2014-04-14 17:35:47

Porlus (86 views)
2014-04-14 15:48:38

tom_mai78101 (109 views)
2014-04-10 04:04:31

BurntPizza (169 views)
2014-04-08 23:06:04

tom_mai78101 (265 views)
2014-04-05 13:34:39

trollwarrior1 (217 views)
2014-04-04 12:06:45
List of Learning Resources
by SHC
2014-04-18 03:17:39

List of Learning Resources
by Longarmx
2014-04-08 03:14:44

Good Examples
by matheus23
2014-04-05 13:51:37

Good Examples
by Grunnt
2014-04-03 15:48:46

Good Examples
by Grunnt
2014-04-03 15:48:37

Good Examples
by matheus23
2014-04-01 18:40:51

Good Examples
by matheus23
2014-04-01 18:40:34

Anonymous/Local/Inner class gotchas
by Roquen
2014-03-11 15:22:30
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!