String getResourceName ( String fileName ) { // FIXME: there is probably a more robust way to do this // Strip off the directory part. String dirPath = directory . getPath ( ) ; if ( ! fileName . startsWith ( dirPath ) ) { throw new IllegalStateException ( "Filename " + fileName + " not inside directory " + dirPath ) ; } // The problem here is that we need to take the relative part of the // filename // and break it into components that we can then reconstruct into // a resource name (using '/' characters to separate the components). // Unfortunately, the File class does not make this task particularly // easy. String relativeFileName = fileName . substring ( dirPath . length ( ) ) ; File file = new File ( relativeFileName ) ; LinkedList < String > partList = new LinkedList <> ( ) ; do { partList . addFirst ( file . getName ( ) ) ; } while ( ( file = file . getParentFile ( ) ) != null ) ; StringBuilder buf = new StringBuilder ( ) ; for ( String part : partList ) { if ( buf . length ( ) > 0 ) { buf . append ( ' ' ) ; } buf . append ( part ) ; } return buf . toString ( ) ; }
Get the resource name given a full filename .