classLoader的线程“main”java.lang.NullPointerException中的异常

时间:2018-05-18 07:41:35

标签: java nullpointerexception classloader

运行代码时出现错误(第10行)。就是这样:

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

第10行是:File txtFile = new File(classLoader.getResource("loginDao.txt").getFile()); 既然它是一个classLoader并且自动必须“完成它的工作”,我不知道出了什么问题。请帮忙!

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;
    }
}

0 个答案:

没有答案