我想使用如下代码得到当前程序文件的绝对路径
public class test{
public static void main(String args[]){
System.out.println(java.io.File.getAbsolutePath());
}
}
编译的时候出现错误
无法从静态上下文中引用非静态 方法 getAbsolutePath()请问有什么好的办法来得到当前程序文件的绝对路径吗?
public class test{
public static void main(String args[]){
System.out.println(java.io.File.getAbsolutePath());
}
}
编译的时候出现错误
无法从静态上下文中引用非静态 方法 getAbsolutePath()请问有什么好的办法来得到当前程序文件的绝对路径吗?
import java.io.*;public class FilePackless{
public static void main(String[] args) {
FilePackless hand = new FilePackless();
hand.fun01();
}
public void fun01() {
String path = this.getClass().getResource(this.getClass().getName()+".java").getPath();
String trim = path.substring(1).replace('/','\\');
System.out.println("name is:"+name+"\npath is:"+path+"\ntrim is:"+trim); }
}顺便请教高手,如果有带包的话怎么处理呢?
System.out.println(ss);
name = name.substring(name.lastIndexOf(".")+1);
name = name+".class";
URL url = this.getClass().getResource(name);
String path = url.getPath();
如果你要用到的文件以下文件的东西
package yjws.util;import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.util.*;/**
* TCP数据包接受处理类
*/
public class Acceptor implements Runnable { private final Selector selector;
private final ServerSocketChannel ssc; public Acceptor(Selector selector, ServerSocketChannel ssc) {
this.selector = selector;
this.ssc = ssc; }
下面文件就可以这样导入上个文件的包import yjws.util.*;
然后就可以用里面public的成员函数了
this.filename = filename; try {
String path = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
saxReader = new SAXReader();
if(path.indexOf("WEB-INF")>0){
path = path.substring(0,path.indexOf("/WEB-INF/classes")+16);
document = saxReader.read(path+filename);
}else{
document = saxReader.read(getClass().getResourceAsStream(filename));
} } catch (Exception ex) {
ex.printStackTrace();
}
}兼容WEB和非WEB应用程序
兼容tomcat weblogic别的有些方法一般在weblogic tomcat下得到的结果不一样