2017-03-03 90 views
0

對於從我的服務器提供的靜態資源(嵌入在JAR中) - 我想要映射它們的內存。內存映射類路徑資源

我寫了下面:

try (InputStream is = getClass().getResourceAsStream(classpathItem)) { 
     byte[] bytes = ByteStreams.toByteArray(is); 

     ByteBuffer directBuffer = ByteBuffer.allocateDirect(bytes.length); 
     directBuffer.put(bytes); 
     directBuffer.flip(); 

     return directBuffer; 
    } 

後來我想通,必須有Java中的選項已經做到這一點(也許JVM參數)。有這樣的事嗎?

回答

0

您可以創建與靜態內容的戰爭。

DIRS:

war 
    WebContent 
    META-INF 
    WEB-INF 
     classes 
     web.xml 
    index.html 
    ... etc static contents 
    build.xml 

的web.xml

<welcome-file-list> 
<welcome-file>index.html</welcome-file> 
</welcome-file-list> 

的build.xml

<target name="war" description="Bundles the application as a WAR file" > 
    <mkdir dir="WebContent/WEB-INF/classes"/> 
    <copy includeemptydirs="false" todir="WebContent"> 
       <fileset dir="../dist"> 
        <include name="**/*.html"/> 
        <include name="**/*.js"/> 
        <include name="**/*.css"/> 
        <include name="*.html"/> 
        <include name="*.js"/> 
        <include name="*.css"/> 
        <include name="**/**/*.png"/> 
       </fileset> 
    </copy> 

    <war destfile="ScadaLTS.war" 
        basedir="WebContent" 
        needxmlfile="false"> 
    </war> 
</target> 

命令編譯:螞蟻戰爭

提供靜態內容可以簡單的戰爭不是創建罐子。

+0

我一點點困惑,請問這個回答我的問題? – Cheetah

+0

這個簡單的解決方案在自己的服務器tomcat上提供靜態內容(資源)。 – Grzesiek

+0

我很抱歉,但這不是我問的問題。簡而言之,我問,「你如何記憶映射類路徑資源?」 – Cheetah

1

這個答案有點晚,但我偶然發現了這個問題。

簡短的回答是否定的,你不能從你的jar中記憶地圖資源。 這是由於資源如何存儲在jar本身中。 jar文件實際上只是一個zip文件,資源是zip文件的內容。這就是您無法獲得File或除了URLInputStream之外的任何內容的原因。 URL只是讓你打開一個InputStreamInputStream本身只是讓你流的資源內容,解壓縮,因爲它去。

有趣的是,如果ZipFileSystem支持內存映射,這將是可能的。

這裏是工作,如果ZipFileSystem支持的內存映射的一個片段:

// Hack to get URL to running jar 
String path = Main.class.getResource("Main.class").toString().split("!")[0]; 
FileSystem fs = FileSystems.newFileSystem(URI.create(path), 
     Collections.singletonMap("create", "true")); 
Path p = fs.getPath("/path/to/my/resource"); 
FileChannel fc = FileChannel.open(p); 
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); 

問題是你得到這樣的:

Exception in thread "main" java.lang.UnsupportedOperationException 
     at com.sun.nio.zipfs.ZipFileSystem$4.map(ZipFileSystem.java:799) 
     at com.example.Main.main(Main.java:25) 

這可能是你不能做的最好這是因爲無論如何,你很可能會得到糟糕的表現。 Zip文件將文件平鋪和壓縮,因此沒有簡單的方法將其展開,而無需先爲自己分配內存映射緩衝區,然後將內容解壓縮到其中。

可能爲時已晚,以幫助你,但它可能會從回事白費力氣後阻止別人:P