1

Currently, I am learning how to program in Java as a hobby. I have done a lot of reading and practicing in NetBeans but I do not have any formal training in the matter. So, if I make a rookie mistake, keep that in mind, please.

Ok, so, I was given a code for how to read a file in Java. I have seen this same code smattered all over the web and on here; I won't be bothering y'all with that. :)

Now, like I said, I have been doing quite a bit of reading and studying and I know the code I was given was crap. (In case you are wondering what I was given, the package was called "textfiles", the class was called "FileData" & "ReadFile" with "readFile" and "OpenFile" as the methods under the "ReadFile" class. Sound familiar?) Anyway, I got sick of that and wrote my own. Now, I am having a bit of a hard time. What am I doing wrong?

Here is my main Class:

package javaclass;

import java.io.IOException;

    public class JavaClass{

    public static void main(String[] args) throws IOException {

        String file_name = "C:/users/Admin/test.txt";
        try {
            Reader rdr = new Reader(file_name);
            System.out.println(rdr.OpenFile());
        }
        catch (IOException e) {

        }


    }
} 

And here is my class for opening and reading the file:

package javaclass;

import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;

public class Reader extends JavaClass{

    private String path;

    public Reader(String file_name) throws IOException {
        String file = path;
    }

    public String OpenFile() throws IOException {
        FileReader fr = new FileReader(path);
        BufferedReader br = new BufferedReader(fr);
        String line = null;
        ArrayList<String> list = new ArrayList<>();        
        while ((br.readLine()) !=null) {
            list.add(line);
        }
        return list.toString();           
    }
}

This is what I am getting when I compile:

Exception in thread "main" java.lang.NullPointerException
at java.io.FileInputStream.<init>(FileInputStream.java:134)
at java.io.FileInputStream.<init>(FileInputStream.java:97)
at java.io.FileReader.<init>(FileReader.java:58)
at javaclass.Reader.OpenFile(Reader.java:17)
at javaclass.JavaClass.main(JavaClass.java:12)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

I have been wracking my brain trying to figure this out. I have looked at the exceptions. Reader.java:17 refers to "FileReader fr = new FileReader(path);" and JavaClass.java:12 refers to "System.out.println(rdr.OpenFile());".

Thank you for your time and advice. :)

4
  • Hint: path is null.
    – Matt Ball
    Sep 16, 2013 at 21:43
  • On Windows, you need to use backslashes for the file paths: "C:\users\Admin\test.txt". You're using the Unix/Linux convention.
    – user377628
    Sep 16, 2013 at 21:43
  • Also, variable names are usually camel-cased in Java, so file_name should be fileName. It's not required, but it's good practice.
    – user377628
    Sep 16, 2013 at 21:47
  • @Hassan, / will work on Windows in Java. Sep 16, 2013 at 22:00

3 Answers 3

4

The stacktrace is telling you what the error is. The variable path has not been assigned when the instance of FileReader is created.

You're assigning file_name to a variable that is never used. Replace

String file = path;

with

path = file_name;

Also don't forget to assign the variable line

while ((line = br.readLine()) != null) {

so that it can be assigned a value to add to the ArrayList

3
  • I made those changes. I seems so easy to forget to add "line" to the "while" statement. NetBeans doesn't throw an error if you forget to leave it so it's easy to overlook. In the Reader method, I had my statement backwards that assigns a value to my instance variable ("String file_name = path;" needs to be "path = file_name;") I also added a "br.close();" to clean up after it's run. Now, here's what happens. When I run, without errors this time, I get "[null, null, null, null]". Do you know why?
    – Rincewind
    Sep 17, 2013 at 13:41
  • Looks like youre still not assigning the line variable. Did you make that change (or possibly running old code)? If the latter is the case try cleaning your project
    – Reimeus
    Sep 17, 2013 at 13:47
  • ---Edit--- I made the changes and now it works. Thank you for the direction. This was all very much appreciated!
    – Rincewind
    Sep 17, 2013 at 14:19
2

You should make this change ->

                    while ((line = br.readLine()) != null) {
                            list.add(line);
                    }
4
  • That's probably true, but the question is why...;) Sep 16, 2013 at 22:07
  • why what? :-) .. I hope you are asking about why I modified a while condition. Earlier "line" was not getting assigned any value and was null. Sep 16, 2013 at 23:48
  • I'm asking you to explain to the user why they should change there code to match your recommendations ;) Sep 17, 2013 at 0:07
  • @MadProgrammer thank you for the insight. MadProgrammer, thank you for the guidance in trying to show me why. I understand that the String line was initialized but wasn't getting anything added to it until I added it to the while method.
    – Rincewind
    Sep 17, 2013 at 13:45
1
while ((br.readLine()) !=null) {
    list.add(line);
}

change :

while (br.ready()) {
    list.add(br.readLine());
}

and

public Reader(String file_name) throws IOException {
    String file = path;
}

change

public Reader(String file_name) throws IOException {
    path = file_name;
}
5
  • 2
    It's probably just that I'm old school, but I'm curious about while ((br.readLine()) !=null) {, I would, personally, have used something more like while ((line = br.readLine()) != null) {. My main concern is, as I read it, that ready only tells you if the next readLine will block or not. While reading a file may be valid a use, I can think of times when a file may "block" (ie reading over a slow network), but certainly if used to read from other streams, it would be of concern to me...just probing for thoughts ;) Sep 16, 2013 at 22:05
  • (sorry, that should have being while (br.ready()) {...copied the wrong text :P - Coffee please!) Sep 16, 2013 at 22:21
  • You're right .I always use buffered reader for reading a text file in local disc and I have never came across the this problem(slow connection). I understood thank you for your interest. Sep 16, 2013 at 22:21
  • @Melih Altıntaş I didn't alter the "while" statement but I added "line" to it; now it reads "while((line = br.hasNext()) !=null) { list.add(line); }". Now, it works. You stated earlier about something about BufferedReader, is that the best way to read a file? What were you saying about a slow network connection? Is there a time frame before BufferedReader returns a null? What would be the best way to read a file? Thank you.
    – Rincewind
    Sep 17, 2013 at 14:17
  • bufferedReader is the best way.The problem is that I always use while (br.ready()) madprogrammer explained this is wrong.Your way is correct you should use while ((line = br.readLine()) != null) and please look stackoverflow.com/questions/5244839/… And please mark this question as solved Sep 17, 2013 at 23:38

Not the answer you're looking for? Browse other questions tagged or ask your own question.