Java获取classpath路径总结
1概述
这里我对异常情况也做了屏蔽,给大家参考一下。资源文件放在资源目录即可。
1.1静态获取
private static
URL currentStaticClassPathResourceUrl
= null;
static {
//1.静态调用:不能加/,而且还没有:
file:
currentStaticClassPathResourceUrl
= Thread.currentThread().getContextClassLoader().getResource("packetText1.txt");
if
(null
== currentStaticClassPathResourceUrl) {
//支持非:JDK7和
JDK8
currentStaticClassPathResourceUrl
= Thread.currentThread().getContextClassLoader().getResource("/packetText1.txt");
}
System.out.println("[static]"
+ currentStaticClassPathResourceUrl.getPath());
}
public void
testImmulateClient2() {
String ip = "127.0.0.1";
int
port = 1500;
PacketImmulateSender packetSender =
new PacketImmulateSender(ip, port,
new File(currentStaticClassPathResourceUrl.getPath()));
Thread senderThread = new
Thread(packetSender);
senderThread.start();
try
{
Thread.sleep(2000
* 60);
} catch
(InterruptedException e) {
e.printStackTrace();
}
System.out.println("SubjectObserverClientTest End.");
}
1.2对象方法获取
public void
testImmulateClient() {
String ip = "127.0.0.1";
int
port = 1500;
URL currentNoStaticClassPathResourceUrl =
null;
//非静态调用:加/
currentNoStaticClassPathResourceUrl =
this.getClass().getResource("/packetText1.txt");
if
(null
== currentNoStaticClassPathResourceUrl) {
currentNoStaticClassPathResourceUrl =
this.getClass().getResource("packetText1.txt");
}
System.out.println("[no-static]"
+ currentNoStaticClassPathResourceUrl.getPath());
PacketImmulateSender packetSender =
new PacketImmulateSender(ip, port,
new File(currentNoStaticClassPathResourceUrl.getPath()));
Thread senderThread = new
Thread(packetSender);
senderThread.start();
try
{
Thread.sleep(2000
* 60);
} catch
(InterruptedException e) {
e.printStackTrace();
}
System.out.println("SubjectObserverClientTest End.");
}