Writing to a resource in Java? -
this question has answer here:
i trying save data file on computer using class.getresource() method. problem returns url. cannot find way write file using url. here code have far:
url = getclass().getresource("save.txt"); urlconnection urlconn = url.openconnection(); outputstream os = urlconn.getoutputstream(); outputstreamwriter isr = new outputstreamwriter(os); buffer = new bufferedwriter(isr);
when run java.net.unknownserviceexception: protocol doesn't support output error. not sure do.
you can't write resource that. it's meant read only.
on other hand, can find out path of resource file. 1 of methods be:
finding out path of resource
public static file findclassoriginfile( class cls ){ // try find 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 file class
, may changed resource well.
what recommend use resource default, copy out of classpath working directory , save there.
copying resource dir
public static void copyresourcetodir( class cls, string name, file dir ) throws ioexception { string packagedir = cls.getpackage().getname().replace( '.', '/' ); string path = "/" + packagedir + "/" + name; inputstream = groovyclassloader.class.getresourceasstream( path ); if( == null ) { throw new illegalargumentexception( "resource not found: " + packagedir ); } fileutils.copyinputstreamtofile( is, new file( dir, name ) ); }
Comments
Post a Comment