java.io.IOException java
java.io.IOException java
我们尝试使用以下代码从文件中获取字节。
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
或 filePath
,因为这就是它的实际名称。
这两个概念(文件和资源)相关但不相同。资源可以是磁盘上的文件,也可以是 jar 文件中的文件,也可以是从远程加载的资源 URL(不经常使用,但可能)。
由于在您的情况下,您知道要访问磁盘上的文件,因此需要使用 FileInputStream
。
另请参阅 以更深入地解释文件、资源和相关概念之间的差异。
我们尝试使用以下代码从文件中获取字节。
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
或 filePath
,因为这就是它的实际名称。
这两个概念(文件和资源)相关但不相同。资源可以是磁盘上的文件,也可以是 jar 文件中的文件,也可以是从远程加载的资源 URL(不经常使用,但可能)。
由于在您的情况下,您知道要访问磁盘上的文件,因此需要使用 FileInputStream
。
另请参阅