Java Can';t从文本文件中读取数据
我有一个名为Java Can';t从文本文件中读取数据,java,file,Java,File,我有一个名为pwd.txt的文本文件,位于projectfolder->src->pwd.txt 我访问此文件的方式如下: File f1 = new File("src\\pwd.txt"); if(f1.exists()==false){ System.out.println("file not"); } FileReader fr = new FileReader(f1); while ((ch = fr.read()) != -1) { pass = pass + (ch
pwd.txt
的文本文件,位于projectfolder->src->pwd.txt
我访问此文件的方式如下:
File f1 = new File("src\\pwd.txt");
if(f1.exists()==false){
System.out.println("file not");
}
FileReader fr = new FileReader(f1);
while ((ch = fr.read()) != -1) {
pass = pass + (char) ch;
}
LoginForm.pwd = pass;
fr.close();
首先,让我告诉您,当在IDE
(Eclipse)中运行时,我可以访问该文件,但当我创建了jar
文件时,我无法访问该文件pwd.txt
。
当我看到该
jar
文件的内容时,我可以看到文件pwd.txt尝试下面的代码,希望它能帮助您
BufferedReader br = null;
//first open the file
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream("src\\pwd.txt")));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
return;
}
try {
String line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
}
br.close();
} catch (IOException e) {
System.out.println("ERROR:"+e);
}
试试下面的代码,我希望它能帮助你
BufferedReader br = null;
//first open the file
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream("src\\pwd.txt")));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
return;
}
try {
String line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
}
br.close();
} catch (IOException e) {
System.out.println("ERROR:"+e);
}
您是从.jar内部还是从.jar外部读取此文件?查一下这张重复的答案。如果在.jar外部,请提供绝对路径。在jar文件中,您不能使用
file
或FileReader
访问或打开压缩在.zip文件中的文件,您需要通过类加载器加载此文件。getClass().getClassloader().getResource(“pwd.txt”)您是从.jar内部还是从.jar外部读取此文件?查一下这张重复的答案。如果在.jar外部,请提供绝对路径。在jar文件中,您不能使用file
或FileReader
访问或打开压缩在.zip文件中的文件,您需要通过类加载器加载此文件。getClass().getClassloader().getResource(“pwd.txt”)我对代码进行了格式化,以便大括号对齐。下次请你自己做。你可以选择任何你想要的大括号和空格的样式,只要保持一致就行了。非常感谢,我是新来的,所以我很感激你的建议,我会记住的。我格式化了你的代码,使大括号对齐得很好。下次请你自己做。你可以选择任何你想要的大括号和空格的样式,只要保持一致就行了。非常感谢,我是新来的,所以我很感激你的建议,我会记住的。