This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm getting a NullPointerException in java (at this line :FileReader fstream = new FileReader(fileName)) when I try to read a text file line by line and store them in an arraylist with this code :
public ArrayList<String> StoreLineByLine(String fileName) throws IOException {
String str;
ArrayList<String> Line = new ArrayList<String>();
FileReader fstream = new FileReader(fileName);
BufferedReader myFileReader = new BufferedReader(fstream);
while ((str = myFileReader.readLine()) != null) {
Line.add(str);
}
myFileReader.close();
return Line;
}
Could anyone help me understand the problem ?
Thanks a lot !
If you're getting a NPE on that line, then fileName must be null.
BTW, if you're using JDK 8 then this may be a better way to load the lines. Replace the contents of your method with this:
return Files.readAllLines(Paths.get(fileName), Charset.defaultCharset());
...and change the method's return type from ArrayList<String> to List<String>.
Related
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Convert array of strings into a string in Java
(14 answers)
Closed last month.
I have a string input file and I put the strings into arrays. I only want to print the last element of each string array onto my console and onto a output array. When I run my code, I get the last element of each string array onto my console, but see this on my output file:
[Ljava.lang.String;#51d5f7fd
How can I print the actual string array to show up on output file and not its string representation? I'll show you my code so you get a better understanding of what I'm trying to do:
try {
br = new BufferedReader(new FileReader("C:\\rd\\bubble.txt"));
//first, create new file object
File file = new File("C:\\rd\\bubble_out.txt");
if(file.exists()) {
file.createNewFile();
}
PrintWriter pw = new PrintWriter(file);
String line = "";
while((line = br.readLine()) != null) { //while the line is not equal to null
String[] arr = line.split("\\s+"); //split at whitespace
System.out.println(arr[arr.length - 1]);
pw.println(arr);
pw.close();
}
}
catch(IOException x)
{
System.out.println("File not found");
}
}
}
}
}
I've tried using Array.toString() method, but I'm not sure how to implement it into my code correctly. I'm currently trying to do that, but if there's an easier way to do this, please let me know.
Use Arrays.toString to get a readable String representation of the array.
Don't close the PrintWriter inside the loop as you have not finished writing all output. You can use try with resources to avoid having to explicitly close it.
try (PrintWriter pw = new PrintWriter(file)) {
while((line = br.readLine()) != null) {
String[] arr = line.split("\\s+");
System.out.println(arr[arr.length - 1]);
pw.println(Arrays.toString(arr));
}
}
This question already has answers here:
Kotlin readln() does not work as intended
(1 answer)
Intellij Idea scanner.nextLine() returns empty String
(1 answer)
Closed 9 months ago.
I'm writing code in Intelij. readLine does not correctly read the input (puts a line break at the end of the line), which is why the next readline does not work (becomes automatically empty).
Code:
public class Start {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String s = reader.readLine();
ArrayList<String> list = new ArrayList<>();
while (true) {
if (s == null || s.isEmpty()) {
break;
}
else list.add(s);
s = reader.readLine();
}
for (String str : list) {
System.out.println(str);
}
If important: LF separator and UTF-8 encoding
It's a known bug in IntelliJ IDEA. The fix is already available, please update.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am tring to read a file which has lines like so:
438782 Abaca bunchy top virus NC_010314 Musa Sp.
So the lines contain information seperated by tabs. I am tring to read this file and do something with every line after splitting them. It keeps throwing a NullPointerException error though. This always happens on the line where I try to split. In the code below I left everything unrelated to this issue out.
BufferedReader br = new BufferedReader(new FileReader(filename));
String nextLine = br.readLine();
String[] line;
while (nextLine != null) {
nextLine = br.readLine();
line = nextLine.split("\t"); //Error line
//Do something with line
}
This line should be the last one inside your while loop, not the first
nextLine = br.readLine();
This question already has answers here:
Reading UTF-8 - BOM marker
(9 answers)
Closed 5 years ago.
I applied this code more than one, this code is to read a file and for each line, it should create a new object and add it to att_agreement ArrayList, it works fine for each line except the first line, I can not find its object in the output.
Any help, please?
public ArrayList<Att_Elements> load_ann(File f) {
ArrayList<Att_Elements> att_agreement = new ArrayList<Att_Elements>();
String line="";
try {
BufferedReader read = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF8"));
while((line = read.readLine()) != null) {
String[] SplitLine = line.split("\\|");
if (SplitLine[0].equals("Att")) {
annotation=new Att_Elements();
annotation.Type = SplitLine[0];
.
.
.
//...
att_agreement.add(annotation);
}
}
read.close();
} catch (IOException e) {
e.printStackTrace();
}
return att_agreement;
}
Here is a sample of file content (3 lines):
Your file likely has what is called a BOM located at the beginning. This is a byte order mark. Thus, your conditional .equals("Att") is not being met until the second line where the BOM is not present. A separate if statement to handle this case should work well. If you print each line read, you should see what the BufferedReader is reading as the first line. The new conditional statement can then be tailored to this value.
Another approach is to search for a generic BOM string and replace it with nothing.
I want to read a CSV file in java and store this data in an array to be able to search using this data in another function.
public ArrayList < Resp > processTextToRespList(String filePath) throws IOException {
ArrayList < data > result = new ArrayList < data > ();
br = new BufferedReader(new FileReader(csvFile));
while((row = BufferedReader.readNext()) != null) {
String line = scan.nextLine();
String[][] lineArray = line.split(" ");
result.add(new esp(lineArray[0], lineArray[1], lineArray[2]));
}
return result;
}
I don't really understand what is your issue, but I guess it has to do with the code you've given. I fixed the obvious mistakes to turn it into something more compilable :
public List < Resp > processTextToRespList(String filePath) throws IOException {
List<Resp> result = new ArrayList<>();
File csvFile = new File(filePath);
try(BufferedReader br = new BufferedReader(new FileReader(csvFile))){
String row;
while((row = br.readLine()) != null) {
String[] lineArray = row.split(" ");
result.add(new Resp(lineArray[0], lineArray[1], lineArray[2]));
}
}
return result;
}
I haven't corrected any logic, I just used the variables you declared instead of the initial non-java code you've written and closed the FileReader.
Tell me if that is enough for you or if your issue is more complex than that.
Explanation :
I've declared the result as a List instead of an ArrayList because it's my own sensibility talking, no real error here.
You've created a FileReader over a csvFile but never declared any csvFile, I assumed it was the File generated from your filePath.
I declared the FileReader and BufferedReader in a try-with-resources block so that they'll be closed automatically.
I called readLine on br because it's the BufferedReader we instantiated, you can't just call a static method (which does not exist) and hope it'll work.
I split the row we just read, and not some line read from a scanner which was never declared.
All in all, I just fixed some obvious errors that probably appeared while copy-pasting some code without any thought. I'm not sure if you did understand what you were writting nor what you were doing.