Click here to Skip to main content
15,123,367 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm pretty new to Java and I'm trying to figure out how I can update a text file with user input. I first make the file with some input and that works but I'd like to update the file with more input.

Thanks so much!

What I have tried:

I tried asking a user for their name and age and I then was able to save in a file but not sure how I can add new users and information to the existing userAge.txt file.
import java.util.*;

class Main{  
    public static void main(String args[]){  
        Scanner scan = new Scanner(;
        System.out.println("Name: ");
        String name =;
        System.out.println("Age: ");
        int age = scan.nextInt();
        System.out.println("Name:" + " " + name + " " + "Age:" + " " + age);

            File file = new File("userAge.txt"); 
            PrintWriter writer = new PrintWriter(file);
            writer.write(name + " " + age);
        } catch(IOException e){


Updated 29-Sep-20 6:17am

1 solution

I figured it out based on This StackOverflow answer

try(FileWriter fw = new FileWriter("userAge.txt", true);
        BufferedWriter bw = new BufferedWriter(fw);
        PrintWriter out = new PrintWriter(bw))
            out.println(name + " " + age);
        } catch (IOException e) {
                    //exception handling left as an exercise for the reader

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900