有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何将数字列表保存在数据库中。java中的txt文件?

因此,我试图用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();
            }
        });
    }
}

共 (0) 个答案