0

My code seems to be throwing a null pointer exception when attempting to copy an existing file to a new location; the new file will also be named based on the current date of execution.

Any ideas?

public static String returnScreenshotName() {
    return (System.getProperty("user.dir") + "\\target\\output\\imgs\\" + screenshotName);
}

private static void copyFileUsingStream(File source, File dest) throws IOException {
    InputStream is = null;
    OutputStream os = null;
    try {
        is = new FileInputStream(source);
        os = new FileOutputStream(dest);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = is.read(buffer)) > 0) {
            os.write(buffer, 0, length);
        }
    } catch (IOException ignored) {
    }
    finally {
        is.close();
        os.close();
    }
}

public static void copyLatestExtentReport() throws IOException {
    try {
        Date d = new Date();
        String date = d.toString().replace(":", "_").replace(" ", "_");
        File source = new File (System.getProperty("user.dir") + "\\output\\report1.html");
        File dest = new File (System.getProperty("user.dir") + "\\output\\" + date + ".html");
        copyFileUsingStream(source, dest);
    }catch (IOException ignored) {
    }

enter image description here

SamP
  • 417
  • 5
  • 24
  • 1
    The first thing I notice is that you are not null-checking before you close your streams in the `finally` block. If for some reason you can't create one or the other this will cause a NPE when you try to call close on them. – Stalemate Of Tuning Feb 04 '19 at 17:25
  • 4
    `catch (IOException ignored) { }` That is not a good idea. Handle the exception, check the message, then you'll see what happened and why `is` was `null`. – rgettman Feb 04 '19 at 17:26
  • @rgettman is right, my guess would be that `is = new ...` fails miserably, throws an exception et voilá. – Ondřej Xicht Světlík Feb 04 '19 at 17:30
  • 1
    Use try-with-resources which was added to Java7 – Naya Feb 04 '19 at 17:36

0 Answers0