Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make program copy file from package to user.dir in java?

Tags:

java

file

I want to create Java program that creates certain HTML files and since they all contain some images, program should also copy those images to the user.dir, where HTML files are created. I have those images in package "resources", code is in package "code". How do I make that happend?

like image 965
kovike Avatar asked Mar 19 '26 17:03

kovike


1 Answers

Basically, you will need a list of the resource files that you wish to copy. Them you use

public class CopyUtil {

  public void doTheCopy( List<String> resourceNames ) {

    for ( String resource : resourceNames ) { 
      InputStream is = this.getClass().getClassLoader().getResourceAsStream(resource);
      FileOutputStream fos =
        new FileOutputStream( new File(System.getProperty("user.dir"), resource));
      byte[] buffer = new byte[1024];
      int read = -1;
      while( (read = is.read(buffer)) != -1 ) {
        fos.write( buffer,0,read);
      }
      fos.flush();
      fos.close();
    }
  }
}
like image 76
Clint Avatar answered Mar 22 '26 07:03

Clint



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!