文件,我做了一個類存儲和從文件中檢索數據,但是當我跑我的代碼有錯誤,比如問題在Java
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;
}
}
沒有人知道如何解決這個問題的驅動程序文件不被創建的文件? 任何幫助,將不勝感激。
路徑顯然是錯誤的。如果您將此應用程序打包到JAR或WAR中,則無法使用文件系統訪問它;你應該使用來自CLASSPATH的輸入流。 – duffymo
你的代碼永遠不會調用'store()',所以你如何期望文件被創建?還請注意,使用相對路徑使得您的程序依賴於您從中啓動它的文件夾。 – Thomas
您還需要使用flush和try-with-resources來使代碼更簡單。 – jrtapsell