2014-04-13 77 views
-1

自从我与文件混淆了很长一段时间。我正在尝试在eclipse中创建一个txt文件,并在此代码中使用它。处理获取文件名,查找文件,扫描它的代码是:从用户输入中扫描文件

System.out.println("Input from a file"); 
System.out.print("Enter file name: "); 
String str = expression.nextLine(); 
int i = 0; 
File file = new File(str); 
Scanner fScan = new Scanner(file); 

我得到的是FileNotFoundExceptions。我的文件与我的所有课程都在同一个文件夹中,我无法在网上找到真正有用的答案。

因此,如果有人能指出我要去的地方错了,这将是巨大的:)

+0

请分享项目结构。 – Braj

+0

我相信你的输入文件路径是错误的。因为,我没有问题 – sancho21

回答

0

所有的你有应该是一个尝试{}内,外有一个catch代码行,那会赶上该FileNotFoundException异常,例如,

Try{ 
/*your code here*/ 
// but try this 
Scanner scannerName = new Scanner("FileName.<extension>"); //extension being .txt, etc 
String str; 
while(scannerName.hasNext());{ 
str = scannerName.nextLine(); 
/*work with str here*/ 
} 
Catch(FileNotFoundException e){ 
System.out.println("File not found"); 
} 
0

如果在同一个包哪里是类文件的文件,那么你可以试试这个也:

Scanner fScan = new Scanner(this.getClass().getResourceAsStream("abc.txt")); 
//do not forget to close the Scanner in the end 
fScan.close() 

展望从资源文件夹

File file = new File("resources/abc.txt"); 

这里文件abc.txt是项目结构

enter image description here

0

你确定该文件是在根文件夹?默认的工作目录是项目目录。

如果您确信您的文件是有那么它的无论是你的错打字的时候你的文件的名称,或somethine其他正在发生的事情,来弄明白,我建议你尝试以下3个试验:

当你键入文件名有没有搞错

1 - 确保

2,尽量把文件的完整路径,看看现在它会发现它

3,尝试把尽可能名称有点像

新文件(“src/pa/Yourinput.txt”)。