I am working on an android app that has to parse text from a file.
I have the following method in my Parser.java class:
private String getText(String fileName) {
BufferedReader buffer = null;
File file = new File(fileName);
try{
buffer = new BufferedReader( new FileReader(file));
}
catch (FileNotFoundException e){
System.out.println("Could not find file" + fileName);
}
String everything = null;
try{
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = buffer.readLine()) != null){
builder.append(line);
builder.append(System.lineSeparator());
line = buffer.readLine();
}
everything = builder.toString();
//buffer.close();
}
catch (IOException e) {
e.printStackTrace();
return null;
}
finally {
if ((buffer != null)) {
try {
buffer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return everything;
}
I am getting an issue whenever there is a call to the buffer.readLine() method within the while loop.
I pass in the following path info the File object is this:
"/Users/aa/Desktop/parser.txt"
Now I have looked at numerous posts on stack and online in order to try and solve this, and have tried using a few solutions from this and this but have had no luck. This is a snippet from the error stack trace that I get.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.io.BufferedReader.readLine()' on a null object reference
at com.example.allanaraujo.parser.Parser.getText(Parser.java:40)
at com.example.allanaraujo.parser.Parser.parse(Parser.java:19)
at com.example.allanaraujo.parser.OpenDocument.uploadButton(OpenDocument.java:62)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I am sure that the path of the file is correct because I checked it while debugging. I am not sure what else I should be considering here.
EDIT: I am developing on OS X not windows or Linux