Java 读取JAR程序所在文件夹中的文本文件时出现问题
我的.jar程序所在的位置有一个文本文件: 主文件夹: |_myJar.jar |_myText.txt 当我运行.jar文件时,我希望它读取myText.txt的内容,但是路径设置为Java 读取JAR程序所在文件夹中的文本文件时出现问题,java,file,text,jar,Java,File,Text,Jar,我的.jar程序所在的位置有一个文本文件: 主文件夹: |_myJar.jar |_myText.txt 当我运行.jar文件时,我希望它读取myText.txt的内容,但是路径设置为String fileName=“./path.txt”它仍然不读取文件。我相信它正在尝试从jar内部读取path.txt文件 我尝试了其他的解决方案,似乎没有一个能告诉程序从jar文件外部读取path.txt文件,所以任何帮助都将不胜感激 代码: public static void readFile() {
String fileName=“./path.txt”代码>它仍然不读取文件。我相信它正在尝试从jar内部读取path.txt文件
我尝试了其他的解决方案,似乎没有一个能告诉程序从jar文件外部读取path.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);
}
}
}
我想,您可以通过类获得文件的完整路径,只需对其进行初始化,该类应该打包在myJar.jar中。只需将示例中的类从jar更改为真实的类
public static void readFile() {
File file = new File(YourClass.class.getProtectionDomain().getCodeSource().getLocation().getFile());
String fileName = file.getParent() + File.separator + "Paths.txt";
...
我想,您可以通过类获得文件的完整路径,只需对其进行初始化,该类应该打包在myJar.jar中。只需将示例中的类从jar更改为真实的类
public static void readFile() {
File file = new File(YourClass.class.getProtectionDomain().getCodeSource().getLocation().getFile());
String fileName = file.getParent() + File.separator + "Paths.txt";
...
使用System.getProperty(“user.dir”)
或new File(“.”
)并将结果打印到控制台,以确保工作目录与您期望的位置相同……您还可以使用File#exits
测试是否存在,这会有所帮助。.使用System.getProperty(“user.dir”)或
或新建文件(“.”
并将结果打印到控制台,以确保工作目录与您期望的位置相同…您还可以使用文件#exits
测试是否存在,这会有所帮助。。