Saad AL-awad Saad AL-awad - 5 days ago 5
Java Question

How to take string input from user's in Java and save it to a txt.file?

I am new in this so I hope some one can help me I want to know How to take string input from user's in Java and save it to a txt. file ? (and please explain how if you can)

Answer

You can use Scanner and FileWriter:

Scanner s = new Scanner(System.in);
String text = s.nextLine();//read input from user
File f = new File("C:\\Users\\itama\\Desktop\\filename.txt");
try {
    FileWriter fw = new FileWriter(f);
    fw.write(text);
    fw.flush();
    fw.close();
} catch (IOException e) {
    e.printStackTrace();
}
Comments