Reading a File

I can't seem to read a file in Java.  The filename is recipies.txt.  It resides in the same folder as my program.  Here is my code...

public static void loadRecipes(RecipeDatabase t, Recipie[] r) {
               
        StringBuffer contents = new StringBuffer();
        BufferedReader input = null;
        File fileName = new File("recipies.txt");
       
        int i = 0;
       
        try {
            input = new BufferedReader( new FileReader(fileName) );
            //String line = null; //not declared within while loop
            //while (( line = input.readLine()) != null && i < 10){
            //    Recipie temp = new Recipie(line, input.readLine(), input.readLine(), input.readLine());
            //    r[i].copyRecipie(temp);
            //    i++;
            //}
        }
        catch (Exception ex){
            JOptionPane.showMessageDialog(null, "File access error!" + ex.toString(), "Alert", JOptionPane.ERROR_MESSAGE);
        }
       
    }

I am getting the error:

File access error! java.io.FileNotFoundException: recipies.txt (The system cannot find the file specified)

NeoTek
LVL 1
NeoTekAsked:
Who is Participating?
 
aozarovCommented:
or:
r[i] = new Recipie(line, input.readLine(), input.readLine(), input.readLine());
i++;

is another way...
0
 
aozarovCommented:
"recepies.txt" should be found in the same folder your are running your java program from
when you are reading it this way.
0
 
neonlinesProject managerCommented:
Ur program works fine.

U check the following

1. Check file permission
2. Do u have package structure in ur program? - If so include the path with file
3. Anyway, include the path upto the file directory in ur CLASSPATH
0
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

 
aozarovCommented:
add after:
File fileName = new File("recipies.txt");
try { System.out.println(fileName.getCanonicalPath()); } catch (Exception ignoreForNow){}
and see if this is really the place you have recepies.txt
0
 
CEHJCommented:
If the file is seldom updated, it would probably be better to load the file from a jar containing your program. That way, it'll never go astray ;-)
0
 
NeoTekAuthor Commented:
Should I put the full path in the file name?

I do not have package structure.

The directory is not in my CLASSPATH.

NeoTek
0
 
aozarovCommented:
Do you have the output from try { System.out.println(fileName.getCanonicalPath()); } catch (Exception ignoreForNow){}
If you provide the full path of the file to new File(...) then it should be found.
Another option is to make sure that recepies.txt is located in the same folder where you run the java program (because this is where java will look for the it when given just the filename).
Also, if recepies.txt is in your CLASSPATH then you can load it via YOUR_CLASS_NAME.class.getResourceAsStream("/rceepies.txt")
or if recepies.txt is located in the same place where you class is then you can load it via YOUR_CLASS_NAME.class.getResourceAsStream("recepies.txt")


0
 
NeoTekAuthor Commented:
fileName.getCanonicalPath() returned:

C:\Program Files\NetBeans3.6\recipies.txt

When I initalize the file with the full path it works.  The problem is, I only want to use a relative path as other people using this will have different locations for the file.

Any ideas?

NeoTek
0
 
CEHJCommented:
The way this is often done is for each user to have the config file in their home directory:


File config = new File(System.getProperty("user.home"), "recipies.txt");
0
 
NeoTekAuthor Commented:
Isn't there an easier way to program this?  The file is located in the same directory as the program.

NeoTek
0
 
CEHJCommented:
I thought there were different files?

>>The problem is, I only want to use a relative path as other people using this will have different locations for the file.

Are there different programs too?
0
 
NeoTekAuthor Commented:
I have one program and one file.  I want the path to be relative to the program directory (actually it is in the same directory as the program).  On my computer it is in the location E:\Test (as an example), if I give this to another person they may put it in (C:\Program).  Do you see what I mean?
0
 
CEHJCommented:
If it's in the same directory this should work:

input = new BufferedReader( new InputStreamReader(getClass().getResourceAsStream("recipies.txt") ) );
0
 
aozarovCommented:
>> input = new BufferedReader( new InputStreamReader(getClass().getResourceAsStream("recipies.txt") ) );
getClass() will not work as a direct replacment as it is called from a static method.

I actually mentioned that above:
YOUR_CLASS_NAME.class.getResourceAsStream("/rceepies.txt") -> in the same folder as your class
YOUR_CLASS_NAME.class.getResourceAsStream("recepies.txt") -> where your application classes are
Those can be different location if your class has a package declaration (will be in the sub folder of the applicaiton classes).

0
 
CEHJCommented:
>>as it is called from a static method

That's true
0
 
NeoTekAuthor Commented:
Ok, here is my modified code...

public static void main(String args[]) {
       
        RecipeDatabase mainForm = new RecipeDatabase();
        Recipie[] recipies = new Recipie[10];
       
        mainForm.show();
        loadRecipes(mainForm, recipies);
       
}
   
public static void loadRecipes(RecipeDatabase t, Recipie[] r) {
               
        StringBuffer contents = new StringBuffer();
        BufferedReader input = null;
        File fileName = new File("recipies.txt");
        try { System.out.println(fileName.getCanonicalPath()); } catch (Exception ignoreForNow){}
       
        int i = 0;
       
        try {
            input = new BufferedReader( new InputStreamReader(RecipeDatabase.class.getResourceAsStream("recipies.txt")) );
            String line = null;
            while (( line = input.readLine()) != null && i < 10){
                Recipie temp = new Recipie(line, input.readLine(), input.readLine(), input.readLine());
                r[i].copyRecipie(temp);
                i++;
            }
        }
        catch (Exception ex){
           
            JOptionPane.showMessageDialog(null, "Error: " + ex.toString(), "Alert", JOptionPane.ERROR_MESSAGE);
        }
       
}

It sees the file, but the following line...

r[i].copyRecipie(temp);

...is getting the error...

NullPointerException.

Any ideas why?

NeoTek
0
 
CEHJCommented:
How is your copyRecipe defined?

r[i] =  temp;

is one way
0
 
CEHJCommented:
I'm wondering why you left this in too ...

>>
 File fileName = new File("recipies.txt");
        try { System.out.println(fileName.getCanonicalPath()); } catch (Exception ignoreForNow){}
>>
0
 
CEHJCommented:
>> How is your copyRecipe defined?

(Although in this case this is academic as r[i] is null anyway). r is a reference to an an array of null references to Recipe
0
 
CEHJCommented:
>> ...  as r[i] is null anyway

This is why you're getting an NPE
0
 
NeoTekAuthor Commented:
public void copyRecipie(Recipie r) {
             
        type = r.type;
        name = r.name;
        description = r.description;
        ingredients = r.ingredients;
       
}
0
 
CEHJCommented:
No need for that - just read it directly into the array. You don't even need an interim variable, as aozarov showed
0
 
NeoTekAuthor Commented:
Thanks guys, it works now.
0
 
aozarovCommented:
Nice. :-))
0
 
CEHJCommented:
:-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.