我正在尝试从应用程序中读取csv文件。但我得到了java.io.FileNotFoundException:。下面是我的csv阅读代码。
String constantURL = AppConst.INTERNAL_ASSETS_CONFIG_ROOT_URL + "whitelist/RMWhitelist.csv";
logger.info("constantURL > " + constantURL);
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try{
br = new BufferedReader(new InputStreamReader(new FileInputStream(constantURL)));
while ((line = br.readLine()) != null) {
String[] country = line.split(cvsSplitBy);
System.out.println("Country [code= " + country[0] + " , name=" + country[1] + "]");
}
}catch(Exception e){
e.printStackTrace();
}下面是我得到的错误。
INFO: constantURL > http://localhost:7001/shops/config/whitelist/milRMWhitelist.csv
java.io.FileNotFoundException: http:\localhost:7001\app\config\whitelist\RMWhitelist.csv (The filename, directory name, or volume label syntax is incorrect)为什么会出现这个错误?路径中提供了CSV文件。
更新
下面是我在另一个项目中使用的现有代码之一。这工作得很好。但是相同的代码在这个新项目中不起作用。获取F.N.F错误。如何区分文件输入流是URL还是来自文件路径?
final String file = this.httpRequestPoster.sendGetRequest(AppUrlConst.CONFIG_URL + "other.csv", "");
Reader reader = new StringReader(file);
final CSVReaderBuilder<UpgradeVO> customerVOCSVReaderBuilder = new CSVReaderBuilder<UpgradeVO>(reader);
customerVOCSVReaderBuilder.strategy(CSVStrategy.UK_DEFAULT);
CSVReader<UpgradeVO> customerVOCSVReader = customerVOCSVReaderBuilder.entryParser(new UpgradeParser()).build();
Iterator<UpgradeVO> customerVOIterator = customerVOCSVReader.iterator();
while (customerVOIterator.hasNext()) {
UpgradeVO upgradeVO = customerVOIterator.next();
logger.info(UpgradeVO.getServiceId());
}发布于 2016-08-25 14:31:23
您正在将FileInputStreams与HTTP URL混合在一起
要么使用一个,要么使用另一个
例如:
InputStream input = new URL(constantUrl).openStream();或
br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));发布于 2016-08-25 14:28:38
您正在向FileInputStream传递一个表示URL的字符串。FileInputStream需要一个指向文件系统的文件名。因此,您的方法不起作用!
换句话说:通过包括主机IP地址和端口号,您的字符串不再“仅仅是一个文件名”。
因此,有两种选择:
发布于 2016-08-25 15:36:16
根据你的评论和对你的问题的更新,我认为这是可行的:
String constantURL = AppConst.INTERNAL_ASSETS_CONFIG_ROOT_URL + "whitelist/RMWhitelist.csv";
File file = new File(constantURL);
String cvsSplitBy = ",";
try(BufferedReader br = new BufferedReader(new InputStreamReader(file.exists()?new FileInputStream(file): new URL(constantURL).openStream()));){
for (String line; (line = br.readLine()) != null;) {
String[] country = line.split(cvsSplitBy);
System.out.println("Country [code= " + country[0] + " , name=" + country[1] + "]");
}
}catch(Exception e){
e.printStackTrace();
}重要的部分是这个file.exists() ? new FileInputStream(file) : new URL(constantURL).openStream(),它检查constantURL是否是本地文件系统上的有效文件路径。如果是,它会打开一个FileInputStream;如果不是,它会尝试打开到的url连接。
https://stackoverflow.com/questions/39138096
复制相似问题