この記事では、Javaがファイルの絶対パスを取得する方法について説明します。参照のためにそれを共有してください。特定の実装方法は次のとおりです。
次のようにコードをコピーします:/**
*クラスのクラスファイルが配置されている絶対パスを取得します。 このクラスは、JDK独自のクラス、ユーザー定義のクラス、またはサードパーティ開発パッケージのクラスです。
*このプログラムでロードできるクラスである限り、クラスファイルの絶対パスに配置できます。
*
* @Param CLS
*オブジェクトのクラス属性
* @Returnこのクラスのクラスファイルの場所への絶対パス。 このクラスに定義がない場合、nullが返されます。
*/
プライベートストリングgetPathfromClass(クラスCLS)はiOExceptionをスローします{
文字列パス= null;
if(cls == null){
新しいnullpointerexception();
}
url url = getClassLocationUrl(CLS);
if(url!= null){
path = url.getPath();
if( "jar" .equalsignorecase(url.getProtocol())){
試す {
path = new url(path).getPath();
}
catch(malformedurlexception e){
}
int location = path.indexof( "!/");
if(location!= -1){
path = path.substring(0、location);
}
}
file file = new file(path.replaceall( "%20"、 ""));
path = file.getCanonicalPath();
}
戻りパス。
}
/**
*クラスファイルの場所のURLを取得します。この方法は、このクラスの最も基本的な方法であり、他の方法を呼び出すためです。
*/
プライベートURL getClassLocationUrl(最終クラスCLS){
if(cls == null){
新しいIllegalargumentException( "入力がnullであるクラス");
}
url result = null;
final string clsasresource = cls.getname()。置き換え( '。'、 '/').concat(".class ");
最終保護ドメインpd = cls.getProtectionDomain();
if(pd!= null){
final codesource cs = pd.getCodesource();
if(cs!= null){
result = cs.getlocation();
}
if(result!= null){
if( "file" .equals(result.getProtocol())){
試す {
if(result.toexternalform()。endswith( "。jar")|| result.toexternalform()。endswith( "。zip")){
result = new url( "jar:"。concat(result.toexternalform())。concat( "!/")。concat(clsasresource));
}
else if(new file(result.getFile())。ISDirectory()){
result = new URL(result、clsasresource);
}
}
catch(malformedurlexceptionは無視){
}
}
}
}
if(result == null){
final classloader clsloader = cls.getClassLoader();
result = clsloader!= null?
}
返品結果;
}
この記事がみんなのJavaプログラミングに役立つことを願っています。