In Console:
Exception in thread "main" java.lang.NullPointerException at SimulatedReality.main(SimulatedReality.java:25)
Line 25 is "BecomesArray = ReadsLine.toCharArray();".
In my code, I am attempting to read off of a file and check all of its characters (or at least for first ten) to see if any are of the value one. I am trying to do this to reset the text of the document after being used once. The problem with the code is that there is a null-pointer error, caused by declaration problems (or, at least, that is what I heard). I couldn't find where this error was. Please and thank you for whoever helps me. I am a beginner, so explanation will be best if overly simplified.
File SRFile = new File("C:/Users/ThinkingBeing/Documents/SRFile.txt");
SRFileWriter = new
FileWriter("C:/Users/ThinkingBeing/Documents/SRFile.txt");
if(!SRFile.exists()){
SRFile.createNewFile();
SRFileWriter.write("000000");
System.out.println("File now exists.");
} else {
for(int i=0;i<=5;i++){
SRFileReader = new BufferedReader(new FileReader(SRFile));
ReadsLine = SRFileReader.readLine();
BecomesArray = ReadsLine.toCharArray();
BasicChar = BecomesArray[i];
if(BasicChar!='0'){
SRFileWriter.write("000000");
System.out.println("File Off Of Counter. Counter Fixed.");
}
}
SRFileWriter.close();
SRFileReader.close();
}
I think I found your issue (and please follow Java naming conventions).
SRFileReader = new BufferedReader(new FileReader(SRFile)); // <-- file reader once
ReadsLine = SRFileReader.readLine();
BecomesArray = ReadsLine.toCharArray();
FileWriter SRFileWriter = new FileWriter
("C:/Users/ThinkingBeing/Documents/SRFile.OUT.txt"); // <-- Don't write to
// your input file while you're reading it.
for(int i=0;i<(BecomesArray != null) ? BecomesArray.length : 0;i++){
// SRFileReader = new BufferedReader(new FileReader(SRFile));
BasicChar = BecomesArray[i];
if(!SRFile.exists()||BasicChar=='1'){
// SRFile.createNewFile(); // <-- Would clear your input file.
SRFileWriter.write("00BOOYTA"); // <-- which was also your output file.
}
}
SRFileWriter.close();
SRFileReader.close();
Several possible problems...
It's possible your file has less than 10 lines.
Then readLine will return null and the next line will fail. Documentation here
ReadsLine = SRFileReader.readLine();
BecomesArray = ReadsLine.toCharArray();
Also you should probably make sure your file exists before you start reading from it.
if(!SRFile.exists()||BasicChar=='1'){
And lastly, I can't quite make out what you're trying to achieve just by reading your code. But there's definitely something off with the logic. I find it odd that BasicChar
is the i-th character of the i-th line for each line.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.