简体   繁体   中英

java.io.IOException java

We trying to get bytes from a file using below code.

getBytes("/home/1.ks");

Before that, we have make sure the file is exists.

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");
        }
    }

Here the output and exceptions

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)

Change your line to :

final InputStream input = new FileInputStream(resource);

While you're at it, change the name of the parameter resource to path or filePath , since that is what it really is.

The two concepts (file and resource) are related but not the same. A resource can be a file on disk, but it can also be a file inside a jar file or it could be a resource loaded from a remote URL (not often used, but possible).

Since in your case, you know that you want to access a file on disk, you need to use FileInputStream .

See also What's the difference between a Resource, URI, URL, Path and File in Java? for a deeper explanation of the differences between files, resources and related concepts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM