我是一名Java初学者,我正在尝试编写一个从现有文本文件中读取数据的程序。我已经尽力了,但它总是说“找不到文件!”。我已经将我的"Test.txt“复制到了包的- src和bin文件夹中。请帮我解决这个问题。我会非常感激的。这是代码-
package readingandwritingfiles;
import java.io.*;
public class ShowFile {
public static void main(String[] args) throws Exception{
int i;
FileInputStream file_IN;
try {
file_IN = new FileInputStream(args[0]);
}
catch(FileNotFoundException e) {
System.out.println("File Not Found!");
return;
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: ShowFile File");
return;
}
do {
i = file_IN.read();
if(i != -1)
System.out.print((char)i);
} while(i != -1);
file_IN.close();
System.exit(0);
}
}发布于 2016-07-22 09:59:19
如果您只是放置Test.txt,那么程序将在项目的根文件夹中查找。示例:项目包-src -class -bin -Test.txt Test.txt需要与src和bin位于同一目录中,而不是位于其中
发布于 2016-07-22 10:06:39
将带有相对路径的字符串(或文件)传递到项目文件夹(如果您的文件位于src文件夹中,则此应为"src/Test.txt",而不是"Test.txt")。
对于读取文本文件,你应该使用FileReader和BufferedReader,BufferedReader有读取完整行的方法,你可以一直读到你发现null。
举个例子:
String path = "src/Test.txt";
try {
FileReader fr = new FileReader(path);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
while(line != null) {
System.out.println(line);
line = br.readLine();
}
br.close();
} catch (Exception ex) {
}发布于 2016-07-22 10:24:46
如果你的文件夹结构是这样的( src文件夹中的Text.txt文件)
+源+Text.txt
然后使用下面的代码
ClassLoader classLoader = ShowFile.class.getClassLoader();
File file = new File(classLoader.getResource("Text.txt").getFile());
file_IN = new FileInputStream(file);或者如果你的文件夹结构是这样的
+源+某个包+Text.txt
然后使用下面的代码
ClassLoader classLoader = ShowFile.class.getClassLoader();
File file = new File(classLoader.getResource("/somepackage/Text.txt").getFile());
file_IN = new FileInputStream(file);https://stackoverflow.com/questions/38516950
复制相似问题