gpt4 book ai didi

java - java中的文件问题

转载 作者:太空宇宙 更新时间:2023-11-04 11:02:15 25 4
gpt4 key购买 nike

我创建了一个类来存储和检索文件中的数据,但是当我运行代码时,我遇到了错误,例如

Error retrieving infojava.io.FileNotFoundException: computer-db.txt (The system cannot find the file specified)
java.io.FileNotFoundException: computer-db.txt (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at testing.Driver.retrieve(Driver.java:63)
at testing.Driver.main(Driver.java:19)
java.lang.NullPointerException
at testing.Driver.retrieve(Driver.java:89)
at testing.Driver.main(Driver.java:19)

每当我运行它时,这都会显示在控制台输出中。我还意识到,当我运行程序时,并未创建该文件

这是我编写的用于存储和读取文件的驱动程序文件

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class Driver {

public static void main(String[] args) {
Computer c1=new Computer();
c1.display();

Computer p=new Computer();
try {
p=retrieve();
} catch (Exception e) {
e.printStackTrace();
}
p.display();

}

public static void store(Computer c) throws IOException {
FileWriter pc=new FileWriter("computer-db.txt");
try {
pc.write(c.getOwnername()+"\t");
pc.write(c.getModel()+"\t");
pc.write(c.getColor()+"\t");
pc.write(c.getCentralprocessingunit().getClockspeed()+"\t");
pc.write(c.getCentralprocessingunit().getManufacturer()+"\t");
pc.write(c.getCentralprocessingunit().getNumcores()+"\n");
} catch(IOException ex) {
System.out.println("error writing to the file "+ex);
} finally {
try {
if(pc != null) {
pc.close();
}
} catch(IOException ex) {
System.out.println("Error with file "+ex);
}
}
}

public static Computer retrieve()throws Exception {
Scanner read=new Scanner(System.in);
Scanner rfile= null;
Computer pc=new Computer();
try {
rfile=new Scanner(new File("computer-db.txt"));
System.out.println("Enter the name to search for: ");
String srcParam = read.next();
while(rfile.hasNext()) {
String ownername=rfile.next();
String model=rfile.next();
String color=rfile.next();
double clockspeed=rfile.nextDouble();
String manufacturer=rfile.next();
int numcores=rfile.nextInt();

if(ownername.equals(srcParam)) {
pc = new Computer(ownername,model,color,clockspeed,
manufacturer,numcores);
break;
}
}
} catch(IOException ex) {
System.out.println("Error retrieving info"+ex);
ex.printStackTrace();
} finally {
rfile.close();
read.close();
}
return pc;
}
}

有谁知道如何解决这个问题吗?任何帮助将不胜感激。

最佳答案

FileNotFoundException 告诉您该文件不存在。您正在尝试打开当前目录中的 computer-db.txt。文件真的存在吗?

关于java - java中的文件问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46773479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com