【发布时间】:2015-11-23 16:11:41
【问题描述】:
我在 .jar 程序所在的位置有一个文本文件:
主文件夹:
|_ myJar.jar
|_ myText.txt
当我运行 .jar 文件时,我希望它读取 myText.txt 的内容,但是将路径设置为 String fileName = "./Paths.txt"; 它仍然无法读取该文件。我相信它正在尝试从 jar 中读取 Paths.txt 文件。
我尝试了其他解决方案,似乎没有人告诉程序从 jar 文件外部读取 Paths.txt 文件,因此非常感谢任何帮助。
代码:
public static void readFile() {
String fileName = "./Paths.txt";
BufferedReader br;
String line;
//Attempts to read fileName
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
try {
// Starts reading the file and adding values to linked hashmap
while ((line = br.readLine()) != null) {
String[] lineSplit1 = line.split("#");
String lineKey = lineSplit1[0];
String lineValue = lineSplit1[1];
hm.put(lineKey, lineValue);
}
} catch(Exception e3) {
errorMessage("Error when trying to read the file and add "
+ "the values to a hashmap");
}
//Attempts to close fileName
try {
br.close();
} catch(IOException e1 ) {
System.out.println("Messed up while trying to close buffered reader");
System.out.println(e1);
}
} catch (FileNotFoundException e1) {
errorMessage("The file " + fileName + " does not exist"
+ "\nI have created the file for you.");
try {
PrintWriter writer = new PrintWriter(fileName, "UTF-8");
writer.println("");
writer.close();
} catch(Exception e2) {
errorMessage("Error while trying to create " + fileName);
}
}
}
【问题讨论】:
-
使用
System.getProperty("user.dir")或new File(".")并将结果打印到控制台以确保工作目录与您期望的位置相同...您也可以使用@987654325 @ 测试是否存在,这可以帮助..