getResourceAsStream方法返回null InputStream

时间:2017-11-28 10:30:30

标签: java csv testing junit

此类读取文件CSV。

public class ReadCSVFile {

    private static final String SEMICOLON_DELIMITER = ";";


    public Map<Integer,Company> listFromFile(String csvFile) throws IOException {

        BufferedReader br = null;

        br = new BufferedReader(new 
        InputStreamReader(ReadCSVFile.class.getResourceAsStream(csvFile)));

        Map<Integer,Company> companyHashMap = new HashMap();

        String line;

        br.readLine();

        while ((line = br.readLine()) != null) {

            int pos = line.indexOf(SEMICOLON_DELIMITER);
            String companyCode = line.substring(0,pos);
            String companyName = line.substring(pos +1, line.length());

            companyHashMap.put(Integer.parseInt(companyCode), new Company(Integer.parseInt(companyCode), companyName));
        }

        return companyHashMap;
    }
}

这是ReadCSVFile类的测试:

public class ReadCSVFileTest {

private ReadCSVFile readCSVFile;

@Before
public void before(){

    readCSVFile = new ReadCSVFile();
}

@Test
public void shouldExtractCompanyFromCSV() throws IOException {

    Map<Integer, Company> result = readCSVFile.listFromFile("test_company_list.csv");
    Assert.assertEquals(2,result.size());
    Assert.assertEquals("Goldman Sachs Group Inc",result.get(65).getCompanyName());
    Assert.assertEquals("Repsol YPF SA (Please refer to Repsol SA and YPF SA)",result.get(66).getCompanyName());
}

最后这是要读取test_company_list.csv的文件,我用来比较测试结果:

 RepRisk Company ID;Company Name
65;Goldman Sachs Group Inc
66;Repsol YPF SA (Please refer to Repsol SA and YPF SA)

测试失败,我收到此消息:

java.lang.NullPointerException
    at java.io.Reader.<init>(Reader.java:78)
    at java.io.InputStreamReader.<init>(InputStreamReader.java:72)
    at app.ReadCSVFile.listFromFile(ReadCSVFile.java:21)
    at ReadCSVFileTest.shouldExtractCompanyFromCSV(ReadCSVFileTest.java:23)

我的课程有什么问题?我认为JUnit设置正确。

ReadCSVFile.java:21就是这一行:

br = new BufferedReader(new InputStreamReader(ReadCSVFile.class.getResourceAsStream(csvFile)));

改为行(ReadCSVFileTest.java:23)

 Map<Integer, Company> result = readCSVFile.listFromFile("test_company_list.csv");

2 个答案:

答案 0 :(得分:2)

请阅读getResourceAsStream文档。

  
      
  • @param所需资源的名称      
        
    • @return A {@link java.io.InputStream}对象或{@code null} if
    •   
    • 找不到具有此名称的资源
    •   
  •   

您确定要发送的csvFile文件是否在正确的路径中?看来你必须使用绝对名称

答案 1 :(得分:0)

我使用这条指令修复了它:

        br = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(csvFile)));

根据此链接的解决方案:click here