0

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?

stollr
  • 6,534
  • 4
  • 43
  • 59
  • 1
    My guess is that `paramsValue` is `null` and the call to `write()` is choking on it. – Tim Biegeleisen Jul 07 '17 at 05:20
  • 2
    what is null - show your stacktrace – Scary Wombat Jul 07 '17 at 05:22
  • Welcome to SO. Put your code in a try-catch construct and in the catch block print the stack trace. If you compile with debugging, then you'll see the line number that threw the exception. See [this](https://stackoverflow.com/q/3988788/2775450) for more detail. – Jeff Holt Jul 07 '17 at 05:28
  • Instead of calling `get(Object key)`, you can also, provided that you are using Java 8, the `HashMap`'s method `getOrDefault(Object key, V defaultValue)`, to prevent the value of being `null`. – MC Emperor Jul 07 '17 at 06:58

1 Answers1

0

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);
M. Prokhorov
  • 3,894
  • 25
  • 39