[英]Why can't my program find my text file I am trying to scan?
我试着把文件放在尽可能多的地方,看看它们中是否有任何一个可以工作。 我也尝试使用直接路径,但这也不起作用。 我有一台 mac,想知道这是否搞砸了。
public static void main(String[] args) throws FileNotFoundException{
String nextString=null;
PopularName nextName;
String[] info=new String[5];
Scanner infile = new Scanner(new File("LastNames.txt"));
...
如果你使用
System.getProperty("user.dir");
您可以获取项目的当前根目录。 所以如果你把一个文件放在那里,你可以阅读如下:
new FileReader(System.getProperty("user.dir") + "/LastNames.txt");
您的代码中有更多错误:
文件路径应该相对于绝对项目的根目录。
public class Main {
public static void main(String[] args) throws FileNotFoundException {
Scanner inFile = new Scanner(new File("file.txt"));
while (inFile.hasNext()) {
System.out.println(inFile.next());
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.