gpt4 book ai didi

java - getResourceAsStream 方法返回 null InputStream

转载 作者:行者123 更新时间:2023-11-28 20:08:05 24 4
gpt4 key购买 nike

此类读取 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");

最佳答案

请阅读getResourceAsStream 文档。

  • @param name name of the desired resource
    • @return A {@link java.io.InputStream} object or {@code null} if
    • no resource with this name is found

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

关于java - getResourceAsStream 方法返回 null InputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47529285/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com