Java中通过classpath路径读取模型(通常是序列化的)或其它资源 —Servlet或其它应用

在某些情况下,譬如模型作为servlet的一部分,直接通过classpath就可以读取模型或其它资源就显得非常的方便,完全不需要考虑路径问题,只需把这些资源文件放在classpath中某一个路径下就可以。这也是我们我们喜欢从流input streams,而不是文件,来读取模型的原因。实际上这些实现非常的容易,看看Lingpipe blog上的一个简单的例子就很清楚。

import com.aliasi.chunk.Chunker;
import com.aliasi.util.Streams;
import java.io.*;

public class ReadModel {

 public static void main(String[] args)
 throws IOException, ClassNotFoundException {

 Chunker chunker = readChunker(args[0]);
 for (int i = 1; i < args.length; ++i)
 System.out.println(chunker.chunk(args[i]));
 }

 static Chunker readChunker(String resourceName)
 throws IOException, ClassNotFoundException {

 InputStream in = null;
 ObjectInputStream objIn = null;
 try {
 in = ReadModel.class
 .getResourceAsStream(resourceName);
 objIn = new ObjectInputStream(in);
 return (Chunker) objIn.readObject();
 } finally {
 Streams.closeInputStream(objIn);
 Streams.closeInputStream(in);
 }

 }
}
in = ReadModel.class.getResourceAsStream(resourceName);
其实这一语句中ReadModel可以任何其它都Ok的,你也可以直接使用this, 如果其调用方法不是静态的。

command 下调用:

> javac -cp lingpipe-3.7.0.jar ReadModel.java

Notice:确保model所在文件路径放在classpath中

Servlets

对于servlets应用环境,把model或资源文件放在classes或jar包所在路径下就行了(通常是WEB-INF/lib)

下面是Lingpipe 上的一个具体构建war包的ant 例子。

 <target name="war" depends="jar">
 <mkdir dir="build/war"/>
 <copy todir="build/war">
 <fileset dir="web"/>
 </copy>

 <mkdir dir="build/war/WEB-INF/lib"/>
 <copy todir="build/war/WEB-INF/lib">
 <fileset file="lingpipe-demos.jar"/>
 <fileset file="../../lingpipe-4.0.0.jar"/>
 <fileset file="../lib/commons-fileupload-1.2.1.jar"/>
 <fileset file="../lib/commons-io-1.4.jar"/>
 <fileset file="../lib/nekohtml-1.9.11.jar"/>
 <fileset file="../lib/xml-apis-2.9.1.jar"/>
 <fileset file="../lib/xercesImpl-2.9.1.jar"/>
 </copy>

 <jar destfile="build/war/WEB-INF/lib/models.jar">
 <fileset dir="../">
 <include name="models/**"/>
 </fileset>
 </jar>

 <jar destfile="build/{app.name}.war">
 <fileset dir="build/war"/>
 </jar>
 </target>

然后你就可以跟一般应用一样在servlet中读取这些模型或资源。

Blog Source:http://lingpipe-blog.com/2009/04/03/reading-models-resources-from-classpath-resources-servle/

 Leave a Reply

(required)

(required)


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

使用腾讯微博登陆

Protected by WP Anti Spam
   
© 2011 Information Retrieval Blog Suffusion theme by Sayontan Sinha