![](/img/trans.png)
[英]Can someone help me with this code, it's not returning the results I want to
[英]I want to save an Arraylist of objects into a file.Can Someone help me with this?
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
)只能自己編寫String
, char
和int
。 如果要將任意對象寫入文件,則需要使用ObjectOutputStream
:
RandomObject rando = new RandomObject();
FileOutputStream fout = new FileOutputStream(FILE_PATH);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(rando);
您可能會發現本教程很有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.