0

The error appears when running the code (line 10). This is it:

Exception in thread "main" java.lang.NullPointerException
at classification.GetExtensionOfFileMain.main(GetExtensionOfFileMain.java:10)

Line 10 is: File txtFile = new File(classLoader.getResource("loginDao.txt").getFile()); Since it is a classLoader and automatically has to "do its job", I don't know what's wrong. Please help!

import java.io.File;

public class GetExtensionOfFileMain {

    public static void main(String[] args) {
        ClassLoader classLoader = GetExtensionOfFileMain.class.getClassLoader();

        File txtFile = new File(classLoader.getResource("loginDao.txt").getFile());
        String fileExtension = getExtensionOfFile(txtFile);
        System.out.println("File extension for loginDao.txt is " + fileExtension);


        File folder = new File("C://src//files");
        String fileExtensionFolder = getExtensionOfFile(folder);
        System.out.println("File extension for C://src//files is " + fileExtensionFolder);
    }

    public static String getExtensionOfFile(File file) {
        String fileExtension = "";
        // Get file Name first
        String fileName = file.getName();

        // If fileName do not contain "." or starts with "." then it is not a valid file
        if (fileName.contains(".") && fileName.lastIndexOf(".") != 0) {
            fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
        }

        return fileExtension;
    }
}
Piro
  • 1,367
  • 2
  • 19
  • 40
redcolors
  • 1
  • 2
  • 1
    Which line is line 10? – deHaar May 18 '18 at 07:43
  • File txtFile = new File(classLoader.getResource("loginDao.txt").getFile()); – redcolors May 18 '18 at 07:46
  • 3
    `classLoader` is not null, but `classLoader.getResource("loginDao.txt")` surely does. Meaning that `loginDao.txt` is not in your classpath – yunandtidus May 18 '18 at 07:54
  • As you already got a "solution" in @yunandtidus' answer, I am going to close this question as a duplicate. – Seelenvirtuose May 18 '18 at 07:57
  • I have loginDao.txt in my classpath now, but the error is still there. – redcolors May 18 '18 at 08:01
  • You should probably split that line into more lines, and make sure `classLoader.getResource("loginDao.txt")` will return null. Then you know for sure that is an error and try to resolve resource loading – Piro May 18 '18 at 08:10
  • I have loginDao.txt in the WEB-INF folder (I use Eclipse as an IDE), maybe I should switch the path to it ? – redcolors May 18 '18 at 08:15

0 Answers0