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);
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
Here is the code:
File tempFile = new File("myTempFile.txt");
tempFile.createNewFile();
File inputFile = new File("Friend_list.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
String currentLine;
while((currentLine = reader.readLine()) != null)
{
String trimmedLine;
trimmedLine = currentLine.trim();
}
In this part of the code, there is a NullPointerException. The exact exception is mentioned below:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke
"String.trim()" because "currentLine" is null at com.company.Main.delete(Main.java:167)
at com.company.Main.main(Main.java:48)
The question is if the string is null then how could it enter the while loop? I cross checked the file, data is there in the file then how could it be null?
I think that this is the actual cause of your problem. (Based on the code that you inappropriately posted as an "answer" - now deleted.)
currentLine = reader.readLine();
trimmedLine = currentLine.trim();
Note that in >>those<< statements, you are NOT testing for null before calling trim().
The code in your question is not the code that causes the problem
Your diagnosis was problematic because (presumably) you didn't pay attention to the line numbers in the stacktrace.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I have the following code:
while (true) {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream());
String result = null;
while (result != "string") {
out.println("string one");
out.flush();
String var = null;
if ((var = in.readLine()) != null) {
var2 = function(login);
out.println(var2);
out.flush();
}
}
}
The flushing is not working correctly, mainly the first iteration of the outer while loop will print both outputs, but then after that there is an odd delay and everything is messed up ("string one" is not printing to the output).
What am I doing wrong?
You are using != tocompare String references which isn't going to do what you thinks, though it doesn't matter because you never change anyway.
Most likely you have a bug at the other end which is why readLine() blocks waiting for some text.
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.
This question already has answers here:
How do I create a file and write to it?
(35 answers)
Closed 9 years ago.
I am taking a number of inputs from the user like Name,age,e-mail etc.. , and I concatenated all these fields with a ":" delimiter
`String line = Anjan+":"+21+":"+abc#abcd.com;`
My question is:
How do I write the String line into a file?
I repeat the process of taking inputs from users. Can somebody explain me, how can I write the line to a file each time, after I am done with reading and concatenating the inputs?
If you are using java 7 it will be quite easy,
public void writerToPath(String content, Path path) throws IOException {
try(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(path,StandardOpenOption.CREATE, StandardOpenOption.APPEND)))){
writer.newLine();
writer.write(content);
}
}
Since Writer implements the AutoClosable interface will the writer and underlying streams be closed when finished or if an exception occur.
public static void write(final String content, final String path)
throws IOException {
final FileOutputStream fos = new FileOutputStream(path);
fos.write(content.getBytes());
fos.close();
}
Try the following code. You can create method and pass values as parameter. It'll append the new line every time. It won't remove existing lines(data)
File logFile = new File( System.getProperty("user.home") + File.separator + "test.txt");
String data = "value";
if(!logFile.exists()){
logFile.createNewFile();
}
FileWriter fstream = new FileWriter(logFile.getAbsolutePath(),true);
BufferedWriter fbw = new BufferedWriter(fstream);
fbw.write(data);
fbw.newLine();
fbw.close();
This question already has answers here:
Android read text raw resource file
(14 answers)
Closed 3 years ago.
I'm currently trying to read a file from (res/raw) by using an InputStream that I dimension like such:
InputStream mStream = this.getResources().openRawResource(R.raw.my_text_file_utf_8);
I then put that into this method to return the values:
public List<String> getWords(InputStream aFile) {
List<String> contents = new ArrayList<String>();
try {
BufferedReader input = new BufferedReader(new InputStreamReader(aFile));
try {
String line = new String();//not declared within while loop
while ((line = input.readLine()) != null ){
contents.add(line);
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
return contents;
}
My problem: It reads all the values as it should, but say if the file is 104 lines long, it will actually return a value of something like 134 total lines with the remaining 30 lines being full of null??
Have checked: Already using UTF-8 format, and double checked that there are literally no blank lines within the document itself...
I thought the way the while loop was written that it couldn't record a line=null value to contents List? Am I missing something here?
Thanks for any constructive information! I'm pretty sure I'm overlooking some simple factoid here though...
Why dont you create HTML for your information and then parse it.