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

后端 未结 2 1901
醉酒成梦
醉酒成梦 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!");
            }
        }
    
    }
    

提交回复
热议问题