-1

I have copied this code from hackerrank. It is working correctly when I run this kind of code (this kind of means, used the System.getenv("OUTPUT_PATH") keyword) but I copy this code to my pc and tried to run that code. But I got the error which is below. Is this System.getenv("OUTPUT_PATH") keyword working only in Hackerrank? I know how to print to a textfiles using buffered writer class but I can't understand about this code line. Please help me to improve my knowledge.

public static void main(String[] args) throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
        String s = "Hello world";
        bw.write(s);
        bw.newLine();
        bw.close();
    }

I see this code in more hackerrank problems and I need to know why we use this... this is the error message,

Exception in thread "main" java.lang.NullPointerException
    at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:226)
    at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:124)
    at java.base/java.io.FileWriter.<init>(FileWriter.java:66)
    at com.company.Main.main(Main.java:8)
Jeewantha Lahiru
  • 324
  • 2
  • 4
  • 15
  • 2
    Welcome to Stack Overflow. Please give details of the error you're seeing - "I get error" isn't nearly as helpful as explaining whether this is a compile-time error or an exception, with the exact message (and stack trace if it's an exception). – Jon Skeet Mar 05 '20 at 05:14
  • @JonSkeet I have updated the Question with the error message – Jeewantha Lahiru Mar 05 '20 at 05:17
  • 1
    Right, so it looks like you don't have an `OUTPUT_PATH` environment variable, so `System.getenv("OUTPUT_PATH")` is returning null, and you're passing that null reference into the `FileWriter` constructor. – Jon Skeet Mar 05 '20 at 05:36
  • @JonSkeet how can I solve this error? – Jeewantha Lahiru Mar 05 '20 at 05:41
  • 2
    Either specify an OUTPUT_PATH environment variable, or find some other way of specifying which file you want to write to - whether that's hard-coding the path, or accepting it via command line arguments. I don't know what file you want to write to or how you want that to be configured, making it hard to help you. – Jon Skeet Mar 05 '20 at 05:52

1 Answers1

-1

I guess you didn't give new File try this :

    public static void main(String args[]) throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter(new File("C:\\Users\\myName\\Desktop\\data.txt")));
        String s = "Hello world";
        bw.write(s);
        bw.newLine();
        bw.close();
    }
}

This works fine for me and the txt file is generated as desired. Let me know if it helps.