2016-05-21 7 views
-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(); 
      } 
     }); 
    } 
} 
+0

[よくある質問](http://stackoverflow.com/help/how-to-ask)を理解するためにヘルプセンターをお読みください。具体的には、[MCVE]の提供方法。 –

+0

[JavaDocs for FileWriter](https://docs.oracle.com/javase/8/docs/api/java/io/FileReader.html)を見て、それに 'append'フラグを渡すか、一連の数値を書きたい場合は、ループが必要です – MadProgrammer

+0

このコメントは何を参照していますか? '//ファイルにデータを書き込んで閉じます。ファイルが正しく閉じられない場所についてのコメントの中でmadProgrammerが説明した内容を参照してください.'このコードは別のQまたはAからコピーされていますか? –

答えて

0

は、一度に1つの文字で動作しますので、tryブロックで、数字のarrayをループして、ファイルに書き出しますIntegerに変換し、フラッシュしたものです終了:

try { 
     BufferedWriter out = new BufferedWriter(new FileWriter(fileName)); 
     for (int numero : array) { 
      out.write(Integer.toString(numero) + "\n"); 
    } 
    out.flush(); 
    out.close(); 
関連する問題