NullPointerException when writing csv file [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I want to write a csv with the opencsv libary, however, when running the code I get a NullPointerException.
public void exportToCSV(ArrayList<Data> list) throws IOException {
log.info("write CSV file");
String writerPath = "C:\\Users\\User\\Desktop\\Output\\output.csv";
CSVWriter writer = new CSVWriter(new FileWriter(writerPath), ';');
//headers
String [] entries = {"ID", "Date"};
writer.writeNext(entries);
List<String[]> data = new ArrayList<String[]>();
for (int m = 0; m < list.size(); m++) {
data.add(new String[] {
list.get(m).getID,
(list.get(m).getDate().toString()==null) ? "null" : list.get(m).getDate().toString(), //Here i get the NullPointerException
});
}
writer.writeAll(data);
writer.close();
}
I guess that getDate() is null, which type is a Timestamp. However, why does my proposed solution not work in writing a String when getDate() is null.
I apprecaite your reply!

list.get(m).getDate().toString()==null should be changed to list.get(m).getDate()==null.
If list.get(m).getDate() is null. Invoking a method on it will cause NullPointerException.

Related

Can't insertRow which contains Strings from file [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Why does println(array) have strange output? ("[Ljava.lang.String;#3e25a5") [duplicate]
(6 answers)
Closed 3 years ago.
I'm trying to read from file and insert in a row, after inserting I'm having this :
[Ljava.lang.String;#7f059c04
[Ljava.lang.String;#855c8af
The Listener, and BufferRead and Inserting file read.
String filepath = "C:\\imdoingjava\\Java3-Projet\\valuesarticles.txt";
File file = new File(filepath);
private class okListener implements ActionListener{
public void actionPerformed(ActionEvent event){
try{
BufferedReader br = new BufferedReader(new FileReader(file));
Object [] tableLines = br.lines().toArray();
for(int i=0; i<tableLines.length; i++){
String line = tableLines[i].toString().trim();
String [] dataRow = line.split("\n");
model.insertRow(0, new Object[] {"", "", dataRow ,""});
}
}
catch(FileNotFoundException fo){
fo.getMessage();
}
}
If I used model.insertRow(0, dataRow); which I commented it, it works but it inserts it in the first column, and I want it in the third.

Java unreported exception reading an input stream [duplicate]

This question already has answers here:
Error message "unreported exception java.io.IOException; must be caught or declared to be thrown" [duplicate]
(5 answers)
Closed 4 years ago.
My code for reading an input stream of numbers and sorts them into an array, returns
error:
unreported exception IOException; must be caught or declared to be thrown
on String lines = br.readLine();
public int[] inputArr() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String lines = br.readLine();
String[] strs = lines.trim().split("\\s+");
int [] a = new int [strs.length];
for (int i = 0; i < strs.length; i++) {
a[i] = Integer.parseInt(strs[i]);
}
return a ;
}
Any help please on this?
BufferedReader.readLine() throws an IOException:
public String readLine() throws IOException {
So any call to it must handle it by either:
Surrounding with try/catch block
Declaring that your method also throws that exception.

How to read a textfile and saving it into an Array? [duplicate]

This question already has answers here:
Java: Reading a file into an array
(5 answers)
Closed 4 years ago.
i would like to build a text data-cleaner in Java, which
cleans the text from Smileys and other special charakter. I wrote a text reader,
but he stops after 3/4 of Line 97 and i just don't know why he does it? Normally he should read the complete text file (ca. 110.000 Lines) and then stop. It would be really nice if could show me where my mistake is.
public class FileReader {
public static void main(String[] args) {
String[] data = null;
int i = 0;
try {
Scanner input = new Scanner("C://Users//Alex//workspace//Cleaner//src//Basis.txt");
File file = new File(input.nextLine());
input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
data[i] = line;
i++;
}
input.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(data[97]);
}
}
Your mistake is here:
String[] data = null;
I would expect this code to throw null pointer exception...
You can use ArrayList instead of plain array if you want to have dynamic re-sizing

BufferedWriter throwing NPE [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to write a value fetched from a hashmap into a file :
public writeToFile(HapshMap<String,String> , String fileName) {
File myFile = new File(filePath);
BufferedWriter bufferedWriter = null;
Writer writer = new FileWriter(myFile,false);
bufferedWriter = new BufferedWriter(writer);
String paramsValue = params.get("NAME");
bufferedWriter.write(paramsValue);
}
In the above code , the key "NAME" is not there in the HashMap.
And it is throwing NPE .Can anyone suggest what can be done and why is NPE getting thrown?
BufferedWriter does throw an NPE when you ask it to write null somewhere.
That is a situation you will have to know about and deal with. For example, replace null value with some well known string that indicates emptiness:
Object nvl(Object value, Object defaultValue) {
return value != null ? value : defaultValue;
}
<...>
String value = nvl(map.get("Name"), ""); // using empty string instead of null
writer.write(value);

What is causing null pointer exception at runtime? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
My code compiles, but I get this error at runtime:
Exception in thread "main" java.lang.ExceptionInInitializerError
at GUI.<init>(GUI.java:46)
at GUI.main(GUI.java:252)
Caused by: java.lang.NullPointerException
at java.util.Objects.requireNonNull(Objects.java:203)
at java.util.Arrays$ArrayList.<init>(Arrays.java:3813)
at java.util.Arrays.asList(Arrays.java:3800)
at db.<clinit>(db.java:23)
... 2 more
This is the code causing the error:
public static String strLine;
public static String[] filearray;
public static List<String> list = Arrays.asList(filearray);
public static void load() throws IOException{
FileInputStream in = new FileInputStream("slist.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
filearray = new String[4];
while ((strLine = br.readLine()) != null) {
for (int j = 0; j < filearray.length; j++){
filearray[j] = br.readLine();
}
}
in.close();
Line 46 referenced in the error:
JList stafflist = new JList(db.list.toArray());
I am trying to load a text file as an Array and add it to the JList stafflist, but I get a runtime error.
It's in your declaration:
public static String[] filearray;
public static List<String> list = Arrays.asList(filearray);
fileArray is null, and you're trying to create a List around it.
You can either initialize fileArray right here:
public static String[] filearray = new String[4];
Or call Arrays.asList(filearray) after putting the values into filearray.
The problem that I see in your code is here:
public static String[] filearray;
public static List<String> list = Arrays.asList(filearray);
You are trying to convert filearray that is null at the time to list using Arrays.asList() method.
You should initialize filearray first.

Categories