我正在创建一个程序,我必须创建一个文件,然后反序列化该文件中的对象。当我为文件命名时,例如“contacts.dat”,我得到FileNotFoundException
。
代码如下:
public static void main(String[] args) {
String inputstring = Input.getString("Please enter the name of the file containing the contacts: ");
TreeMap< String, Contact > contactlist = null;
ObjectInputStream in;
try {
in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(inputstring)));
contactlist = (TreeMap< String, Contact >) in.readObject();
in.close();
}
catch(ClassNotFoundException | EOFException emptyexcptn) {
System.out.println("The file provided is currently empty.");
contactlist = new TreeMap< String, Contact >();
}
catch(IOException ioexcptn) {
ioexcptn.printStackTrace(System.out);
System.out.println("Error reading file: " + inputstring);
System.exit(1);
}
以下是打印异常的内容:
java.io.FileNotFoundException:contacts.dat(系统找不到指定的文件) at java.io.FileInputStream.open0(Native Method) 在java.io.FileInputStream.open(FileInputStream.java:195) 在java.io.FileInputStream。(FileInputStream.java:138) 在java.io.FileInputStream。(FileInputStream.java:93) 在UnitEight.AssignmentEight.main(AssignmentEight.java:16) 读取文件时出错:contacts.dat
答案 0 :(得分:0)
您对new FileInputStream()
的论证是String inputstring = Input.getString("Please enter the name of the file containing the contacts: ");
...如果Input.getString
返回文件的路径,那么您无论如何都指向错误的路径。
打印Input.getString()
的结果......如果有的话,那会让你知道那里发生了什么。
答案 1 :(得分:-1)
来自API文档 -
构造函数详细信息
FileInputStream
public FileInputStream(String name)抛出FileNotFoundException
通过打开与实际文件的连接来创建FileInputStream,该文件由文件系统中的路径名称命名。创建一个新的FileDescriptor对象来表示此文件连接。
首先,如果有安全管理器,则使用name参数作为参数调用其checkRead方法。
如果指定的文件不存在,则是目录而不是常规文件,或者由于某些其他原因无法打开以进行读取,则会抛出FileNotFoundException。
参数:name - 依赖于系统的文件名.Throws:FileNotFoundException - 如果文件不存在,则是目录而不是常规文件,或者由于某些其他原因无法打开以进行读取.SecurityException - 如果是安全性manager存在且itscheckRead方法拒绝对文件的读访问。
总结一个工作示例:
当您使用FileInputStream(String filename)时,请通过指定文件的完整(绝对)路径来尝试它,以便程序可以找到它。例如:如果你的text.dat文件在共享驱动器Z上:你的String必须作为参数传递给构造函数
“Z:\\ text.dat”而不是使用特定于操作系统的斜杠字符,最好在上面的示例中使用File.separator,它看起来像“Z”+ File.separator +“text.dat”。