public void savemap (File file)
      {
        if (file == null) {
          if (chooser == null) chooser = createChooser();
          chooser.setDialogType(JFileChooser.SAVE_DIALOG);
          int r = chooser.showDialog(this, null);
          if (r != JFileChooser.APPROVE_OPTION) return;
          file = chooser.getSelectedFile();
        }                           /* get the selected file */
        try {                       /* save the current TSP */
          FileWriter writer = new FileWriter(file);
          writer.write();
          writer.close(); }
        catch (IOException e) {
          String msg = e.getMessage();
          this.stat.setText(msg); System.err.println(msg);
          JOptionPane.showMessageDialog(this, msg,
            "Error", JOptionPane.ERROR_MESSAGE);
        }                           /* set the status text */
        this.curr = file;           /* note the new file name */
      }


已编辑

 try {
            int rows = 50;
            int columns = 50;
            Cell [][] cellArray = new Cell[columns][rows];

            FileOutputStream fout = new FileOutputStream(FILE_PATH);
            ObjectOutputStream oos = new ObjectOutputStream(fout);
            oos.writeObject(cellArray);
        }


//这是我更改代码的地方。这是对的吗?但是我在(FILE_PATH)有一个错误
FILE_PATH无法解析为变量

最佳答案

详细说明一下:调用writer.write( )时,它希望您为它提供一个参数,告诉它要写什么。如果没有该参数,则不应编译您的代码。

String s = "foobar"
writer.write(s)


要不就:

writer.write("foobar")


String值写入文件。

您遇到的第二个问题是FileWriter(或更准确地说,它是从其派生的Writer)只能自己编写Stringchar s和int。如果要向文件写入任意对象,则需要使用ObjectOutputStream

RandomObject rando = new RandomObject();
FileOutputStream fout = new FileOutputStream(FILE_PATH);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(rando);


您可能会发现this教程很有用。

10-05 17:51
查看更多