【问题标题】:Keep getting cast exception error when I'm reading a data file? [duplicate]读取数据文件时不断出现转换异常错误? [复制]
【发布时间】:2016-02-03 00:51:14
【问题描述】:

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

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

 {
      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");

     }

【问题讨论】:

  • 请发布您遇到的异常情况
  • store1的类型是什么?
  • @ManosNikolaidis 我收到了 write 方法的不可序列化异常和 read 方法的强制转换异常。
  • @Suds2 如果你需要帮助,你将不得不分享GroceryStore的代码
  • 写作时你永远不会flushclose

标签: java


【解决方案1】:

乍一看,阅读的代码似乎想把它快速放到 GroseryStore 类中,可能需要一些解析才能将其放入其中。尝试 System.out.println 阅读器的输入,然后您就知道自己拥有什么,然后将其解析/切分并切成您需要/想要的内容。

所以,第二个为读/写操作创建一个类。作为简单文本输出文件的写入可能如何工作的示例,您可以使用以下内容:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-07
    • 1970-01-01
    相关资源
    最近更新 更多