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. :)