How to export jar with images on Eclipse?

前端 未结 3 822
Happy的楠姐
Happy的楠姐 2021-01-14 05:27

I created sort of chess game (it isn\'t exactly chess but I don\'t know how it called in English) and I want to export it as runnable jar.

The problem is that image

3条回答
  •  醉酒成梦
    2021-01-14 06:02

    Let me put a couple of examples in case you may find them interesting:

    To write the resource (image) from jar file into a DataOutPutStream:

    public static void readResourceFromJarToDataOutputStream(String file,
            DataOutputStream outW) {
        try {
            InputStream fIs = new BufferedInputStream(new Object() {
            }.getClass().getResourceAsStream(file));
            byte[] array = new byte[4096];
            for (int bytesRead = fIs.read(array); bytesRead != -1; bytesRead = fIs
                    .read(array)) {
                outW.write(array, 0, bytesRead);
            }
            fIs.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    

    To load the resource in memory (byte array):

    public static byte[] readResourceFromJarToByteArray(String resource) {
        InputStream is = null;
        byte[] finalArray = new byte[0];
        try {
            is = new Object() {
            }.getClass().getResourceAsStream(resource);
            if (is != null) {
                byte[] array = new byte[4096];//your buffer size
                int totalBytes = 0;
                if (is != null) {
                    for (int readBytes = is.read(array); readBytes != -1; readBytes = is
                            .read(array)) {
                        totalBytes += readBytes;
                        finalArray = Arrays.copyOf(finalArray, totalBytes);
                        System.arraycopy(array, 0, finalArray, totalBytes- readBytes, 
                                readBytes);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return finalArray;
    }
    

提交回复
热议问题