Java读取相对路径文件怎么读取不了?求助

import java.util.Scanner;

public class ReadData {
public static void main(String[] args) throws Exception {
// Create a File instance
java.io.File file = new java.io.File("scores.txt");

// Create a Scanner for the file
Scanner input = new Scanner(file);

// Read data from a file
while (input.hasNext()) {
String firstName = input.next();
String mi = input.next();
String lastName = input.next();
int score = input.nextInt();
System.out.println(
firstName + " " + mi + " " + lastName + " " + score);
}

// Close the file
input.close();
}
}
文件内容为: John T Smith 90 Erik K Jones 85
源代码如上,文件也放在同一个包里,但编译出错
Exception in thread "main" java.io.FileNotFoundException: scores.txt (系统找不到指定的文件。)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.(Unknown Source)
at java.util.Scanner.(Unknown Source)
at Exercise20.ReadDateScanner.main(ReadDateScanner.java:11)

用ReadData.class.getResourceAsStream("scores.txt")传入scanner

FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null; //用于包装InputStreamReader,提高处理性能。因为BufferedReader有缓冲的,而InputStreamReader没有。
try {
String str = "";
String str1 = "";
fis = new FileInputStream("c:\abc.txt");// FileInputStream
// 从文件系统中的某个文件中获取字节
isr = new InputStreamReader(fis);// InputStreamReader 是字节流通向字符流的桥梁,
br = new BufferedReader(isr);// 从字符输入流中读取文件中的内容,封装了一个new InputStreamReader的对象
while ((str = br.readLine()) != null) {
str1 += str + "\n";
}
// 当读取的一行不为空时,把读到的str的值赋给str1
System.out.println(str1);// 打印出str1

读取相对路径不行,那就用绝对路径。

你可以把文件从src到你的包下面到处拖拖,没放到一个地方执行以下,就能找出来规律,到底应该放在什么地方,需不需要用./或者/。自己试试印象深刻

不同的工具会有细微的差别,比如eclipse与idea。不同的读取方式,也会有区别,下面是一个简单的例子。

1、在Java开发工具的project中使用相对路径
在project中,相对路径的根目录是project的根文件夹,在此就是repathtest文件夹了。
创建文件的写法是:
File f = new File("src/com/lavasoft/res/a.txt");

File f = new File("doc/b.txt");

注意:
路径不以“/”开头;
脱离了IDE环境,这个写法就是错误的,也并非每个IDE都如此,但我见到的都是这样的。

2、通过CLASSPATH读取包内文件
读取包内文件,使用的路径一定是相对的classpath路径,比如a,位于包内,此时可以创建读取a的字节流:
InputStream in = ReadFile.class.getResourceAsStream("/com/lavasoft/res/a.txt");
有了字节流,就能读取到文件内容了。
到底应该放在什么地方,需不需要用./或者/。自己用不同的数据试试,那么自己的印象会更深刻深刻。