Java无法写入.txt

发布于 2024-10-10 01:24:49 字数 4505 浏览 4 评论 0原文

你好,我非常需要你的帮助,我有一个带有 jcombobox 和 3 个文本字段的 jframe,我想要在文本字段中写入的任何内容以及在组合框中所做的选择写入 .txt 我尝试了很多东西,但什么也没有,文件正在创建为 Orders.txt 但仍为空白:S 这是我的代码,我感谢任何帮助,谢谢:)

public class addSalesMan extends JFrame {
    private JComboBox namesJComboBox;
    private JTextField text1;//gia to poso
    private JTextField text2;//thn perigrafh
    private JTextField text3;//kai to numero ths paragelias kai ola auta tha egrafontai sto Orders.txt
    private JButton okJbutton;
    private String names[] = {"Basilis Komnhnos", "Iwanna Papadhmhtriou"};
   public String amount,name,description,number;

    public addSalesMan() {
        super("Προσθήκη παραγγελιών");
        setLayout(new FlowLayout());//dialegoume to flowlayout
//        TextFieldHandler handler = new TextFieldHandler(); writer.write(string);



            //ftiaxonoume to combobox gia tn epilogi tou onomatos
        namesJComboBox = new JComboBox(names);//orizmos JCOMBO BOX
        namesJComboBox.setMaximumRowCount(2);//na emfanizei 2 grammes
                     add(namesJComboBox);
             namesJComboBox.addItemListener(new ItemListener() {
            //xeirozome to simvan edw dhladh tn kataxwrisei ston fakelo         
           public void itemStateChanged(ItemEvent event) {
//prosdiorizoyme an eina epilegmeno to plaisio elegxou
                if (event.getStateChange() == ItemEvent.SELECTED) {                 

                            name = (names[namesJComboBox.getSelectedIndex()]);

//                            writer.newLine();             
                 setVisible(true);
            }
                 }
        });   //telos touComboBOx


        //dimioutgw pediou keimenou me 10 sthles gia thn kathe epilogh kai veveonomaste oti tha mporoume na ta epe3ergasoume kanontas ta editable

        text1 = new JTextField("Amount",10);
add(text1);
        text2 = new JTextField("Description",10);
add(text2);
        text3 = new JTextField("Order Number",10);
add(text3);

        TextFieldHandler handler = new TextFieldHandler();
        text1.addActionListener(handler);
        text2.addActionListener(handler);
        text3.addActionListener(handler);

        //private eswterikh clash gia ton xeirismo twn events twn text
//button kataxwrisis
 okJbutton=new JButton("Καταχώρηση");
 add(okJbutton);
 ButtonHandler bhandler=new ButtonHandler();
 okJbutton.addActionListener(bhandler);

    Order order=new Order(name,amount,description,number);
      Order.addOrders(name,amount,description,number);

    }
    private class ButtonHandler implements ActionListener{
        public void actionPerformed(ActionEvent bevent ){

             JOptionPane.showMessageDialog(addSalesMan.this,String.format("Η Καταχωρηση ήταν επιτυχής",bevent.getActionCommand()));


        }
    }
       private class TextFieldHandler implements ActionListener {
            //epe3ergasia twn simvantwn me kathe enter t xrhsth

            public void actionPerformed(ActionEvent evt) {
                String amount,description,number;
                amount=text1.getText();
                description=text2.getText();
                number=text3.getText();
                text1.selectAll();
                text2.selectAll();
                text3.selectAll();

              }
      if(evt.getSource()==text1 && evt.getSource()==text2 && evt.getSource()==text3){
        JOptionPane.showMessageDialog(addSalesMan.this,String.format("Η Καταχωρηση ήταν επιτυχής",evt.getActionCommand()));

           }
      }

//actionperformed telos
            //ean o xrhsths patisei enter sthn kathe epilogh antistixi kataxwrisi sto

            }


          public static void main(String args[]) {
       java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
        new addSalesMan().setVisible(true);
            }
 });
      }
    }

作者在另一个班级。这是相关代码:

public static void addOrders(String name,String amount,String description,String o_number){
    FileOutputStream fout;
    try {
        FileWriter fstream = new FileWriter("Orders.txt");
        if(name!=null){
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(name);
            out.write(amount);
            out.write(description);
            out.write(o_number);
            out.write("\t\n");
            out.close();
        }
    } catch (IOException e) {
        System.err.println ("Unable to write to file");
        System.exit(-1);
    }
}

hello i desperately need your help,well i have a jframe with a jcombobox and 3 textfields i want anything i write in the textfields and the choice i make in the combobox to be written in a .txt i tried so many things but nothing , the file is being created as Orders.txt but remains blank :S this is my code i appreciate any help Thanks :)

public class addSalesMan extends JFrame {
    private JComboBox namesJComboBox;
    private JTextField text1;//gia to poso
    private JTextField text2;//thn perigrafh
    private JTextField text3;//kai to numero ths paragelias kai ola auta tha egrafontai sto Orders.txt
    private JButton okJbutton;
    private String names[] = {"Basilis Komnhnos", "Iwanna Papadhmhtriou"};
   public String amount,name,description,number;

    public addSalesMan() {
        super("Προσθήκη παραγγελιών");
        setLayout(new FlowLayout());//dialegoume to flowlayout
//        TextFieldHandler handler = new TextFieldHandler(); writer.write(string);



            //ftiaxonoume to combobox gia tn epilogi tou onomatos
        namesJComboBox = new JComboBox(names);//orizmos JCOMBO BOX
        namesJComboBox.setMaximumRowCount(2);//na emfanizei 2 grammes
                     add(namesJComboBox);
             namesJComboBox.addItemListener(new ItemListener() {
            //xeirozome to simvan edw dhladh tn kataxwrisei ston fakelo         
           public void itemStateChanged(ItemEvent event) {
//prosdiorizoyme an eina epilegmeno to plaisio elegxou
                if (event.getStateChange() == ItemEvent.SELECTED) {                 

                            name = (names[namesJComboBox.getSelectedIndex()]);

//                            writer.newLine();             
                 setVisible(true);
            }
                 }
        });   //telos touComboBOx


        //dimioutgw pediou keimenou me 10 sthles gia thn kathe epilogh kai veveonomaste oti tha mporoume na ta epe3ergasoume kanontas ta editable

        text1 = new JTextField("Amount",10);
add(text1);
        text2 = new JTextField("Description",10);
add(text2);
        text3 = new JTextField("Order Number",10);
add(text3);

        TextFieldHandler handler = new TextFieldHandler();
        text1.addActionListener(handler);
        text2.addActionListener(handler);
        text3.addActionListener(handler);

        //private eswterikh clash gia ton xeirismo twn events twn text
//button kataxwrisis
 okJbutton=new JButton("Καταχώρηση");
 add(okJbutton);
 ButtonHandler bhandler=new ButtonHandler();
 okJbutton.addActionListener(bhandler);

    Order order=new Order(name,amount,description,number);
      Order.addOrders(name,amount,description,number);

    }
    private class ButtonHandler implements ActionListener{
        public void actionPerformed(ActionEvent bevent ){

             JOptionPane.showMessageDialog(addSalesMan.this,String.format("Η Καταχωρηση ήταν επιτυχής",bevent.getActionCommand()));


        }
    }
       private class TextFieldHandler implements ActionListener {
            //epe3ergasia twn simvantwn me kathe enter t xrhsth

            public void actionPerformed(ActionEvent evt) {
                String amount,description,number;
                amount=text1.getText();
                description=text2.getText();
                number=text3.getText();
                text1.selectAll();
                text2.selectAll();
                text3.selectAll();

              }
      if(evt.getSource()==text1 && evt.getSource()==text2 && evt.getSource()==text3){
        JOptionPane.showMessageDialog(addSalesMan.this,String.format("Η Καταχωρηση ήταν επιτυχής",evt.getActionCommand()));

           }
      }

//actionperformed telos
            //ean o xrhsths patisei enter sthn kathe epilogh antistixi kataxwrisi sto

            }


          public static void main(String args[]) {
       java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
        new addSalesMan().setVisible(true);
            }
 });
      }
    }

The writers are in another class. Here is the relevant code:

public static void addOrders(String name,String amount,String description,String o_number){
    FileOutputStream fout;
    try {
        FileWriter fstream = new FileWriter("Orders.txt");
        if(name!=null){
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(name);
            out.write(amount);
            out.write(description);
            out.write(o_number);
            out.write("\t\n");
            out.close();
        }
    } catch (IOException e) {
        System.err.println ("Unable to write to file");
        System.exit(-1);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏见 2024-10-17 01:24:49

看来主要问题是您在构造函数中调用 Order.addOrders() 。相反,您应该在用户选择保存其选择时调用它。我假设您希望在用户按下按钮时发生这种情况。因此应该将代码添加到按钮的 ActionListener 中。

您可能需要尝试的是当用户关闭框架时刷新并关闭编写器。

将以下内容添加到框架的构造函数中:

addWindowListener(new WindowAdapter(){
    public void windowClosing(WindowEvent e){
        writer.flush();
        writer.close();
    }
});

当用户关闭框架时,上面的代码将刷新并关闭编写器。

您的代码不清楚,所以我不确定 writer 变量是在哪里声明的,我只是假设它是一个类级别变量。

此外,如果您想向文件添加行而不是每次都覆盖它,则需要以“追加”模式打开文件。这可以通过以下方式实现:

new FileWriter(yourFilePath, true); // set append to true

It looks like the main problem is that you are calling Order.addOrders() in your constructor. Instead, you should call it when a user chooses to save it's selection. I assume you would like this to happen when the user presses the button. So the code should be added in the button's ActionListener.

What you might need to try is flushing and closing the writer when a user closes your frame.

Add the following to the constructor of your frame:

addWindowListener(new WindowAdapter(){
    public void windowClosing(WindowEvent e){
        writer.flush();
        writer.close();
    }
});

The above code will flush and close the writer when a user closes the frame.

Your code is unclear, so I'm not sure where the writer variable is declared, I'm just assuming it is a class level variable.

Also, you need to open your file in 'append' mode if you want to add lines to the file instead of overwriting it every time. This can be achieved through the following:

new FileWriter(yourFilePath, true); // set append to true
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文