Artikel ini menjelaskan metode untuk mendapatkan jalur absolut file oleh Java. Bagikan untuk referensi Anda. Metode implementasi spesifik adalah sebagai berikut:
Salin kode sebagai berikut:/**
* Dapatkan jalur absolut di mana file kelas dari suatu kelas berada. Kelas ini dapat menjadi kelas JDK sendiri, kelas yang ditentukan pengguna, atau kelas dalam paket pengembangan pihak ketiga.
* Selama itu adalah kelas yang dapat dimuat dalam program ini, ia dapat ditemukan ke jalur absolut file kelasnya.
*
* @param cls
* Atribut kelas suatu objek
* @return jalur absolut ke lokasi file kelas kelas ini. Jika tidak ada definisi untuk kelas ini, NULL dikembalikan.
*/
Private String getPathFromClass (kelas CLS) melempar ioException {
String path = null;
if (cls == null) {
lempar nullpointerexception baru ();
}
Url url = getClassLocationUrl (cls);
if (url! = null) {
path = url.getPath ();
if ("jar" .equalsignorecase (url.getProtocol ()) {
mencoba {
path = URL baru (path) .getPath ();
}
Catch (Malformedurlexception e) {
}
int location = path.indexof ("!/");
if (location! = -1) {
path = path.substring (0, lokasi);
}
}
File file = file baru (path.replaceall ("%20", ""));
path = file.getCanonicalPath ();
}
Jalur pengembalian;
}
/**
* Dapatkan URL lokasi file kelas. Metode ini adalah metode paling mendasar dari kelas ini dan adalah untuk metode lain untuk dihubungi.
*/
URL Pribadi GetClassLocationUrl (CLS Kelas Akhir) {
if (cls == null) {
Lempar IllegalArgumentException baru ("Kelas input itu nol");
}
Hasil URL = NULL;
string terakhir clsasResource = cls.getname (). ganti ('.', '/').concat(".class ");
Final ProtectionDomain PD = cls.getProtectionDomain ();
if (pd! = null) {
Kode akhir CS = PD.GetCodesource ();
if (cs! = null) {
hasil = cs.getLocation ();
}
if (hasilnya! = null) {
if ("file" .equals (result.getProtocol ())) {
mencoba {
if (hasil.
result = URL baru ("jar:". concat (result.toExternalform ()). concat ("!/"). concat (clsasResource));
}
lain jika (file baru (result.getFile ()). isDirectory ()) {
hasil = URL baru (hasil, clsasResource);
}
}
Catch (Malformedurlexception Abaikan) {
}
}
}
}
if (result == null) {
classloader final clsloader = cls.getClassLoader ();
hasil = clsloader! = null?
}
hasil pengembalian;
}
Saya harap artikel ini akan membantu pemrograman Java semua orang.