我们尝试使用以下代码从文件中获取字节。
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)
将您的线路更改为:
final InputStream input = new FileInputStream(resource);
在此过程中,将参数的名称更改resource
为path
or filePath
,因为它确实是这样。
这两个概念(文件和资源)相关但不相同。资源可以是磁盘上的文件,也可以是 jar 文件中的文件,也可以是从远程 URL 加载的资源(不经常使用,但可能)。
由于在您的情况下,您知道要访问磁盘上的文件,因此需要使用FileInputStream
.
另请参阅Java 中的资源、URI、URL、路径和文件有什么区别?更深入地解释文件、资源和相关概念之间的差异。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句