You can't write to a resource like that. It's meant to be read only.
On the other hand, you can find out the path of the resource file.
One of methods could be:
Finding out the path of a resource
public static File findClassOriginFile( Class cls ){
// Try to find the class file.
try {
final URL url = cls.getClassLoader().getResource( cls.getName().replace('.', '/') + ".class");
final File file = new File( url.getFile() ); // toString()
if( file.exists() )
return file;
}
catch( Exception ex ) { }
// Method 2
try {
URL url = cls.getProtectionDomain().getCodeSource().getLocation();
final File file = new File( url.getFile() ); // toString()
if( file.exists() )
return file;
}
catch( Exception ex ) { }
return null;
}
The method above finds a file for a Class
, but may be easily changed to a resource as well.
What I would recommend is to use the resource as default, copy it out of the classpath to some working directory and save there.
Copying a resource to dir
public static void copyResourceToDir( Class cls, String name, File dir ) throws IOException {
String packageDir = cls.getPackage().getName().replace( '.', '/' );
String path = "/" + packageDir + "/" + name;
InputStream is = GroovyClassLoader.class.getResourceAsStream( path );
if( is == null ) {
throw new IllegalArgumentException( "Resource not found: " + packageDir );
}
FileUtils.copyInputStreamToFile( is, new File( dir, name ) );
}