Java 为什么我不能在我的项目中访问这个.txt文件?
因此,我有以下代码来检查名为Doctors.txt的文本文件 它有以下信息:Java 为什么我不能在我的项目中访问这个.txt文件?,java,eclipse,Java,Eclipse,因此,我有以下代码来检查名为Doctors.txt的文本文件 它有以下信息: 35000 2000 AV122258C Dr Alex James CARDIO 30500 2005 AB347433C Miss Elizabeth Kooper MB 32653 1995 JA103240B Dr Mohammed Khan ON 64400 2001 JG371458A Dr Tom Jacob CARDIO 910
35000 2000 AV122258C Dr Alex James CARDIO
30500 2005 AB347433C Miss Elizabeth Kooper MB
32653 1995 JA103240B Dr Mohammed Khan ON
64400 2001 JG371458A Dr Tom Jacob CARDIO
91000 2002 IH102411Y Dr Rahana Mohammed ON
55000 1987 JJ405626N Dr Mary Francis AN
87000 1988 WQ333452N Mr Mark Cromwell NEURO
60500 1998 HK413942S Mr Victor Jacob GASTRO
40000 2003 AJ103006X Dr Mia Larson GS
42000 2003 ER148468D Dr Rizwan Hussain GS
38000 2004 RB193984P Dr Lam Yeng HAE
该类文件本身
import java.io.PrintWriter;
import java.io.FileReader;
import java.util.Scanner;
import java.io.IOException;
public class FileHandler
{
/**
* Save all doctor records to a file
* @param doctors the DoctorList to save
*/
public void saveRecords(DoctorList doctors)
{
PrintWriter writer = null;
try
{ // NB: the file name is hard-coded
writer = new PrintWriter("Doctors.txt");
writer.println(doctors.toString());
writer.flush();
}
catch(IOException e)
{
System.out.println("Error writing file");
}
finally
{
writer.close();
}
}
/**
* Load doctor records from the file
* @param doctors the DoctorList to add doctors to
*/
public void readRecords(DoctorList doctors)
{
FileReader reader = null;
try
{
// NB: the file name is hard-coded
reader = new FileReader("Doctors.txt");
Scanner sc = new Scanner(reader);
String record;
String[] data;
Doctor doctor;
while(sc.hasNextLine())
{
record = sc.nextLine();
if(record.length() != 0)
{
data = record.split("\t", 5);
doctor = DoctorFactory.newDoctor(data[3], data[0], data[2], data[1], data[4]);
doctors.add(doctor);
}
}
}
catch(IOException e)
{
System.out.println("Error reading file");
e.printStackTrace();
}
}
}
我把它放在同一个区域内,如下所示:
但是,当我运行主类时,它似乎无法读取内容…路径是您的问题。试试这个:
reader = new FileReader("src/Doctors.txt");
更好的解决方案是不依赖文件路径,使用
getResourceAsStream()
从CLASSPATH
返回InputStream
,路径是您的问题。试试这个:
reader = new FileReader("src/Doctors.txt");
更好的解决方案是不依赖文件路径,在应用程序运行时使用
getResourceAsStream()
从CLASSPATH
返回InputStream
。在构建时,文本“file”通常位于Jar中。它可以通过URL读取,但不能写入
对于这种“持久性”风格的资源,通常的策略是将它们放在
user.home
的子目录中,然后在应用程序运行时通过文件访问它们。在构建时,文本“file”通常位于Jar中。它可以通过URL读取,但不能写入
对于这种“持久性”风格的资源,通常的策略是将它们放在user.home
的子目录中,然后通过File