【发布时间】:2019-03-08 09:16:02
【问题描述】:
我正在尝试制作一种实用方法来从 Spring Boot 中的资源中读取文本文件。为了阅读文件,我以InputStreams 的身份面对他们:
Resource resource = new ClassPathResource(fileLocationInClasspath);
InputStream resourceInputStream = resource.getInputStream();
(注意Resource#getInputStream 抛出 IOException)
然后我尝试使用stupid scanner tricks 中提到的扫描仪,而不是Reader 或其他东西,因为这是一种优雅而简单的方法。
但是,我无法摆脱问题标题中提到的警告。即使我只是简单地调用scanner.close()(在 java-8 方式之前),警告仍然存在。
尝试 #1(第一次尝试):
public static String readFileFromResources(String fileName) throws IOException {
try (Scanner sc = new Scanner(new ClassPathResource(fileName).getInputStream()).useDelimiter("\\A")) {
return sc.next();
}
}
尝试 #2:
public static String readFileFromResources(String fileName) throws IOException {
Scanner sc = new Scanner(new ClassPathResource(fileName).getInputStream()).useDelimiter("\\A");
String text = sc.next();
sc.close();
return text;
}
尝试 #3(警告消失):
public static String readFileFromResources(String fileName) throws IOException {
try (Scanner sc = new Scanner(new ClassPathResource(fileName).getInputStream()).useDelimiter("\\A")) {
return sc.next();
} catch (Exception e) // Note Exception class
{
throw new IOException(e); //Need to catch this later
}
}
有人可以解释为什么 try#1 和 try#2 会引发警告吗?我猜 try #3 没有,因为我们捕获了所有可能的异常。但是唯一可以抛出的异常是来自getInputStream() 方法的IOException。如果Scanner 怀疑任何异常,为什么不强制我们捕获这个异常呢?毕竟,不建议使用Exception 捕获异常。
最后,我想,也许这是一个 STS(Spring 工具套件)问题?
(如果有任何作用-> JDK版本:1.8.0_191)
【问题讨论】:
-
请注意,您参考的文章是2004年写的,那是很久以前的事了。文章中提到的东西可能已经过时了。
-
@MCEmperor 是的,我注意到了,我完全理解你的意思。如果这是问题所在,那么不应该弃用
Scanner#useDelimeter吗?或至少在文档中的内容? -
useDelimiter没有问题。我的评论只是对文章年代的一般警告。 -
@MCEmperor 你确定吗? i.imgur.com/gZQyDpl.png
-
好吧,我应该说“
useDelimiter应该不是问题。但我无法重现它,因为我没有使用 Eclipse。我然而,怀疑调用useLocale而不是useDelimiter会以同样的方式发出警告。
标签: java spring exception java.util.scanner try-with-resources