提问者:小点点

当我读取数据文件时,继续出现强制转换异常错误?[重复]


所以我正在尝试编写和读取一个数据文件,并在读取数据文件后声明一个类型为“杂货店”的新变量。我在运行程序时不断收到转换异常错误。有人可以向我解释为什么会发生这种情况以及如何解决它吗?谢谢。

这是我的写入数据文件方法:

 {
      FileOutputStream file = null;
      ObjectOutputStream outStream = null;
      file = new FileOutputStream(new File(filename));
      outStream = new ObjectOutputStream(file);

      outStream.writeObject(store1);
      System.out.print(filename + " was written\n");

   }

这是我的读取数据文件方法

 {
      FileInputStream file = null;
      ObjectInputStream inStream = null;
      file = new FileInputStream(new File(filename));
      inStream = new ObjectInputStream(file);

      GroceryStore newStore = (GroceryStore) inStream.readObject();
      store1 = newStore;
      System.out.print(filename + " was read\n");

     }

共1个答案

匿名用户

乍一看用于阅读的代码,它似乎想将其快速放入GrosseyStore类,可能需要进行一些解析才能将其放入其中。尝试System.out。打印来自读取器的输入,然后你知道你有什么,然后解析/剪切并将其分割成你需要/想要的内容。

因此,第二步为读/写操作创建一个类。作为简单文本输出文件写操作的示例,您可以使用以下内容:

private String file_name = "FileName";
private String file_extention = ".txt";

BufferedWriter writer = null;

public void writeTextToFile(String stuff_to_file) {
    // trying to write (and read) is a bit hazardous. So, try, catch and finally
    try {
        File file = new File(file_name + file_extention);

        FileOutputStream mFileOutputStream = new FileOutputStream(file);
        OutputStreamWriter mOutputStreamWriter = new OutputStreamWriter(mFileOutputStream);
        writer = new BufferedWriter(mOutputStreamWriter); 

        writer.write(stuff_to_file); // and finally we do write to file

        // This will output the full path where the file will be written to.
        System.out.println("\nFile made, can be found at: " + file.getCanonicalPath()); 
    } catch (Exception e) { // if something went wrong we like to know it.
        e.printStackTrace();
        System.out.println("Problem with file writing: " + e);
    } finally {
        try { // Close the writer regardless of what happens...
            writer.close();
    } catch (Exception e) { // yes, even this can go wrong
                e.printStackTrace();
            } // close try / catch
        } // close finally
   } // close method