Question

I am trying to copy the image files from resource folder to local system with using following code.

  InputStream inStream = null;
  OutputStream outStream = null;
  File bfile = new File(directoryPath + "/icons/" + outputFileName);
  inStream = MyClass.class.getClassLoader().getResourceAsStream("/images/" + imgFileName);
  try {

        outStream = new FileOutputStream(bfile);

        byte[] buffer = new byte[1024];

        int length;

        if (inStream != null && outStream != null) {
            // copy the file content in bytes
            while ((length = inStream.read(buffer)) > 0) {

                outStream.write(buffer, 0, length);

            }

            inStream.close();
            outStream.close();
        } 
        System.out.println("File is copied successful!");

    } catch (IOException e) {
        e.printStackTrace();
    }

This code works absolutely fine when I run through eclipse. But when i build the product, icons are not getting copied to local system.

I also tried

inStream = MyClass.class.getResourceAsStream("/images/" + imgFileName);

but no luck.

Any thoughts!

Was it helpful?

Solution

For opening an input stream consider using FileLocator API:

    FileInputStream is = null;
    FileOutputStream fo = null;
    FileChannel inputChannel = null;
    FileChannel outputChannel = null;
    File bfile = new File(directoryPath + "/icons/" + outputFileName);
    try {
        is = FileLocator.openStream(Activator.getDefault().getBundle(), new Path("/images/" + imgFileName), false);
        inputChannel = is.getChannel();
        fo = new FileOutputStream(bfile);
        outputChannel = fo.getChannel();
        outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
    } finally {
        // close everything in finally
    }

Also, please note, that it is better to close streams and channels in the finally block

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top