Click here to Skip to main content
15,071,581 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.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

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

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

        }
        

    }  
}
Posted
Updated 29-Sep-20 5:17am
v2

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