How to read from user's input in Java and write it to a file

后端 未结 2 1891
醉酒成梦
醉酒成梦 2020-12-11 14:08

I want to create a simple stand-alone application that will take some input from user (some numbers and mathematical functions f(x,y...)) and write them to a file. Then with

相关标签:
2条回答
  • 2020-12-11 14:23

    This is the way I would write to a file. I will let you convert this code into your GUI for practice. See more on BufferedWriter and FileWriter

    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.util.Scanner;
    
    public class Files {
    
        public static void main(String args[]){
    
            System.out.print("Enter Text: ");
            Scanner scan = new Scanner(System.in);
            String text = scan.nextLine();
            FileWriter fWriter = null;
            BufferedWriter writer = null;
            try {
              fWriter = new FileWriter("text.txt");
              writer = new BufferedWriter(fWriter);
              writer.write(text);
              writer.newLine();
              writer.close();
              System.err.println("Your input of " + text.length() + " characters was saved.");
            } catch (Exception e) {
                System.out.println("Error!");
            }
        }
    
    }
    
    0 讨论(0)
  • 2020-12-11 14:26

    For your second question, you may like to consider having a JTextField on your JFrame for the user to enter lines into instead of a JOptionPane. It's just a simple text box, and you can add the box's contents to the file every time the button is pressed:

    public static void main(String[] args) {
        JTextField myTextField = new JTextField();
        // Your code, set size and position of textfield
        panel.add(myTextField);
    }
    
    class ButtonHandler implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            String text = myTextField.getText();
            myTextField.setText("");
            new BufferedWriter(new FileWriter("text.txt")).write(text).newLine().close();
            // the rest of your code
        }
    }
    
    0 讨论(0)
提交回复
热议问题