What is the difference between Class.getResource() and ClassLoader.getResource()?

前端 未结 7 1952
情歌与酒
情歌与酒 2020-11-22 02:25

I wonder what the difference is between Class.getResource() and ClassLoader.getResource()?

edit: I especially want to know if any cachi

7条回答
  •  孤城傲影
    2020-11-22 03:21

    I tried reading from input1.txt which was inside one of my packages together with the class which was trying to read it.

    The following works:

    String fileName = FileTransferClient.class.getResource("input1.txt").getPath();
    
    System.out.println(fileName);
    
    BufferedReader bufferedTextIn = new BufferedReader(new FileReader(fileName));
    

    The most important part was to call getPath() if you want the correct path name in String format. DO NOT USE toString() because it will add some extra formatting text which will TOTALLY MESS UP the fileName (you can try it and see the print out).

    Spent 2 hours debugging this... :(

提交回复
热议问题