- 论坛徽章:
- 0
|
如何得到代码相对目录的路径?
假设这个代码文件是test.java
放在myjsp中
String path="F:\\myjsp\\";
String FileName="regEx.txt";
ReadLocalfile myLocalfile =new ReadLocalfile();
regEx=myLocalfile.getFileContet(path,FileName);
如果我test.java放到其他目录下,也能用用,如何获得执行文件现对路径的绝对路径?
public class test
{
public static void main(String args[])
{
ReadLocalfile myLocalfile =new ReadLocalfile();
String path="F:\\myjsp\\";
String FileName="regEx.txt";
String Webtext=myLocalfile.getFileContet(path,FileName);
System.out.println(Webtext);
}
}
/*
输入本地文件。
*/
import java.io.*;
public class ReadLocalfile{
static public String getFileContet(String path,String FileName)
{
String totalStr="";
File f=new File(path,FileName);
if(f.exists()){//检查File.txt是否存在
try{
FileReader fr=new FileReader(path+FileName);//建立FileReader对象,并实例化为fr
//对FileReader类生成的对象使用read()方法,可以从字符流中读取下一个字符。
BufferedReader br=new BufferedReader(fr);//建立BufferedReader对象,并实例化为br
String Line="";
//判断读取到的字符串是否不为空
int i=0;
do{
i++;
Line=br.readLine();//从文件中继续读取一行数据
if(Line!=null)
totalStr=totalStr+Line;
}while(Line!=null);
br.close();
fr.close();
return totalStr;
}catch(IOException e){
System.out.println("读文件出错" ;
return null;
}
finally{
}
}else{
System.out.println("文件不存在!" ;//输出目前所在的目录路径
}
return null;
}
} |
|