我们试图使用下面的代码从文件中获取字节。
getBytes("/home/1.ks");在此之前,我们必须确保文件是存在的。
public static void getBytes(final String resource) throws IOException {
File file = new File(resource);
if (file.exists()) {
System.out.println("exists");
} else {
System.out.println("not exists");
}
final InputStream input = APIController.class.getResourceAsStream(resource);
if (input == null) {
throw new IOException(resource);
} else {
System.out.println("Not null");
}
}这里的输出和异常
exists
java.io.IOException: /home/1.ks
at com.example.demo.controller.APIController.getBytes(APIController.java:164)
at com.example.demo.controller.APIController.transactionSale(APIController.java:89)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)发布于 2018-06-04 06:09:54
将您的行改为:
final InputStream input = new FileInputStream(resource);在进行此操作时,将参数resource的名称更改为path或filePath,因为这才是真正的名称。
这两个概念(文件和资源)是相关的,但并不相同。资源可以是磁盘上的文件,但也可以是jar文件中的文件,也可以是从远程URL加载的资源(不经常使用,但可能使用)。
因为在您的示例中,您知道要访问磁盘上的文件,所以需要使用FileInputStream。
还请参阅What's the difference between a Resource, URI, URL, Path and File in Java?,以更深入地解释文件、资源和相关概念之间的差异。
https://stackoverflow.com/questions/50674225
复制相似问题