如何在java中的.txt文件中保存数字列表?

时间:2016-05-21 01:03:12

标签: java

所以,我试图在java中创建一个程序,通过从JOptionPane的用户输入中获取数字来保存数字列表,并将其存储到文本文件中。我的代码很好用,但它不能保存所有数字。我不知道我做错了什么。这是我到目前为止所拥有的

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();
            }
        });
    }
}

1 个答案:

答案 0 :(得分:0)

使用BufferedWriter一次只能处理一个字符,因此在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();