-2
私は、JOptionPaneからのユーザ入力から数値を取り出し、テキストファイルに保存することで数字のリストを保存するプログラムをJavaで作成しようとしています。私が持っているコードは素晴らしいですが、すべての数字を保存することはできません。私が間違っていることは分かりません。ここで私はこれまでBufferedWriterのを使用してjavaの.txtファイルの数字のリストを保存するには?
package savenumbers;
import java.awt.Component;
import javax.swing.JOptionPane;
import java.io.*;
import javax.swing.JFileChooser;
public class SaveNumbers {
public static void personInput() {
int contador, numeros, array[];
numeros = Integer.parseInt(JOptionPane.showInputDialog("¿How many numbers?: "));
array = new int[numeros];
for (contador = 0; contador < numeros; contador++)
array[contador] = Integer.parseInt(JOptionPane.showInputDialog("Enter " + numeros + " numbers"));
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("./"));
Component yourWindowName = null;
int actionDialog = chooser.showSaveDialog(yourWindowName); //where the dialog should render
if (actionDialog == JFileChooser.APPROVE_OPTION) {
File fileName = new File(chooser.getSelectedFile() + ".txt"); //opens a filechooser dialog allowing you to choose where to store the file and appends the .txt mime type
if (fileName == null)
return;
if (fileName.exists()) //if filename already exists
{
actionDialog = JOptionPane.showConfirmDialog(yourWindowName,
"Replace?");
if (actionDialog == JOptionPane.NO_OPTION) //open a new dialog to confirm the replacement file
return;
}
try {
BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
out.write(numeros);
out.close(); //write the data to the file and close, please refer to what madProgrammer has explained in the comments here about where the file may not close correctly.
} catch (Exception ex) {
System.err.println("Error: " + ex.getMessage());
}
}
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
personInput();
}
});
}
}
[よくある質問](http://stackoverflow.com/help/how-to-ask)を理解するためにヘルプセンターをお読みください。具体的には、[MCVE]の提供方法。 –
[JavaDocs for FileWriter](https://docs.oracle.com/javase/8/docs/api/java/io/FileReader.html)を見て、それに 'append'フラグを渡すか、一連の数値を書きたい場合は、ループが必要です – MadProgrammer
このコメントは何を参照していますか? '//ファイルにデータを書き込んで閉じます。ファイルが正しく閉じられない場所についてのコメントの中でmadProgrammerが説明した内容を参照してください.'このコードは別のQまたはAからコピーされていますか? –