从硬盘读一个.txt文件。
ReadFile rf = new ReadFile("D:\\Workspaces\\MyEclipse 9\\ajax_listener\\src\\ReadFile\\config.txt"); //这是绝对路径写法,可以用
ReadFile rf = new ReadFile("./src/ReadFile/config.txt"); //这是我试的两种相对路径,但是都读不出来
ReadFile rf = new ReadFile("src/ReadFile/config.txt"); 要读文件在工程中位置
ReadFile rf = new ReadFile("D:\\Workspaces\\MyEclipse 9\\ajax_listener\\src\\ReadFile\\config.txt"); //这是绝对路径写法,可以用
ReadFile rf = new ReadFile("./src/ReadFile/config.txt"); //这是我试的两种相对路径,但是都读不出来
ReadFile rf = new ReadFile("src/ReadFile/config.txt"); 要读文件在工程中位置
ReadFile rf = new ReadFile("config.txt");
标准的IO提供FileReader
将config.txt放到工程根目录下后,可以
FileReader fr=new FileReader("config.txt")
看一下怎么实现的不就知道了吗
获得的值就是工程的根目录,所以这样做也是一种可行的方案
虽然不是最安全的方案
你在命令行下,在别的目录使用 java -classpath {classesfilepath} MainClass 运行试试
ReadFile rf = new ReadFile(path.substring(0,path.lastIndexOf("/"))+"/config.txt");
手写的,没试过,应该可以
获取服务器路径 然后private string uploadFolder = "../ReadFile/";
String path = this.getClass().getResource("config.txt").getPath();
ReadFile rf = new ReadFile(path);
ReadFile.class.getResource("config.txt")
public class ReadFile {
private String fileName;
public ReadFile(String fileName)
{
this.fileName = fileName;
}
public String[] ReadSqlConfig()
{
try
{
int paramCount;
String tempLine;
File file;
BufferedReader buffer = null;
file = new File(fileName);
buffer = new BufferedReader(new FileReader(file));
tempLine = buffer.readLine();
paramCount = Integer.parseInt(tempLine.split(":")[1]);
String[] bufferStr = new String[paramCount];
for(int i= 0 ; i < paramCount;i++)
{
bufferStr[i] = (buffer.readLine()).split(":")[1];
}
return bufferStr; }
catch(IOException e)
{
e.printStackTrace();
return null;
}
}
}
给你回复的方法你试了没?
看了你这个代码,还给个法子
将config.txt文件放在工程根目录下,然后FileReader fr=new FileReader("config.txt")
你试试有效么
src平级的地方,然后测试程序:File file = new File("./ReadFile/xxx.txt");
if (file.exists()) {
System.out.println("Yes, file exists!");
} else {
System.out.println("Sorry, file doesn't exist.");
}我的会输出Yes, file exists!你再看看。
按照你的写法在eclipse中放到ajax_listener目录下面是可以获取到config.txt的。
不过换了环境一样有问题。ReadFile.class.getResource("config.txt");
ReadFile.class.getResource("/ReadFile/config.txt");
ReadFile.class.getClassLoader().getResource("ReadFile/config.txt");通过上面的方式都可以获取到config.txt文件,而不受环境约束。