0

I am trying to save data to a file on my computer using the Class.getResource() method. The problem is that it returns a URL. I cannot find a way to write to the file using the url. Here is the code that I have so far:

url = getClass().getResource("save.txt");
URLConnection urlconn = url.openConnection();
OutputStream os = urlconn.getOutputStream();
OutputStreamWriter isr = new OutputStreamWriter(os);
buffer = new BufferedWriter(isr);

When I run this i get a java.net.UnknownServiceException: protocol doesn't support output error. I am not sure what to do.

Ondra Žižka
  • 43,948
  • 41
  • 217
  • 277
jonathan54
  • 11
  • 1
  • 3

1 Answers1

4

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 ) );
}
Ondra Žižka
  • 43,948
  • 41
  • 217
  • 277