Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/384.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java.io.IOException java_Java_File_Resources - Fatal编程技术网

java.io.IOException java

java.io.IOException java,java,file,resources,Java,File,Resources,我们正在尝试使用下面的代码从文件中获取字节 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");

我们正在尝试使用下面的代码从文件中获取字节

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


有关文件、资源和相关概念之间的差异的更深入解释,请参见

您是否调试并检查了异常的原因?@Stultuske异常的原因是
if(input==null){throw new IOException(resource);}
OP在代码中抛出它。