If you are building standalone application in Java, Maven is your friend when packing your application,
There are two way to let Maven package your application, either as a single jar with all your dependencies jar.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
One advantage if you choose to do this way is if you need to sign your application jar.
This is needed if you are building a Java Web Start client and you need more access than connecting back to the server.
To read more about have Maven signing your jar read http://maven.apache.org/plugins/maven-jar-plugin/usage.html.
But if you choose to go this way, make sure that all license agreement are shipped with your one single jar.
Another way is to let Maven package your source code only and then referring the dependent jar file from the MANIFEST file.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>se.msc.adapter.Main</mainClass>
<classpathPrefix>lib/</classpathPrefix>
</manifest>
</archive>
</configuration>
</plugin>
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
public class Main {
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(new FileInputStream("15370720.pdf4"), "utf-16");
LineNumberReader lnr=new LineNumberReader(isr);
String line = null;
while((line=lnr.readLine())!=null){
System.out.println(lnr.getLineNumber()+"\t"+line);
}
}
}
兩個方法的區別是資源的定義不同, 一個主要用于相對與一個object取資源,而另一個用于取相對于classpath的
資源,用的是絕對路徑。
在使用Class.getResourceAsStream 時, 資源路徑有兩種方式, 一種以 / 開頭,則這樣的路徑是指定絕對
路徑, 如果不以 / 開頭, 則路徑是相對與這個class所在的包的。
在使用ClassLoader.getResourceAsStream時, 路徑直接使用相對于classpath的絕對路徑。
舉例,下面的三個語句,實際結果是一樣的:
com.explorers.Test.class.getResourceAsStream("abc.jpg")
= com.explorers.Test.class.getResourceAsStream("/com/explorers/abc.jpg")
= ClassLoader.getResourceAsStream("com/explorers/abc.jpg")