WHAT'S NEW?
Loading...

Saved data into a text file in java


FileWriter is meant for writing streams of characters. A FileWriter(File file,boolean append) constructors.
file - a File object to write to
append - if true, then bytes will be written to the end of the file rather than the beginning.

Without specifying boolean value to true, it will overwrite every time you add new items. Here are the codes:

import java.io.*;
import java.util.*;
public class Fileinputtext
{
    static Scanner input = new Scanner(System.in);
    public static void main(String[]args)throws IOException
    {
        String name,fname,lname;
        double hoursworked;
        double payrate;
        char ch;
        File f = new File("test.txt");
        try
        {
            //true so that not to overwrite while saving data to a textfile
            FileWriter fw = new FileWriter(f,true);
            System.out.println("Enter your firstname: ");
            fname = input.nextLine();
            System.out.println("Enter you lastname: ");
            lname = input.nextLine();
            System.out.println("Enter your hoursworked:");
            hoursworked = input.nextDouble();
            System.out.println("Enter your payrate:");
            payrate = input.nextDouble();
           
            name = fname + " " + lname;
           
            fw.write("Name: " +name + " Hoors worked: " + hoursworked + " Payrate: " + payrate + ":");
         
            //compute();
            System.out.println("Success");
            fw.close();
            System.out.println("Do you want to see the computed output? y/n: ");
            ch = input.next().charAt(0);
            switch (ch)
            {
                case 'y':
                case 'Y':
                compute();
                break;
                case 'n':
                case 'N':
                System.out.println("System will automatically closed");
                default:
                System.out.println("Error");
                break;
            }
        }catch (Exception ex){
            System.out.println("Error");
        }
       
    }
    public static void compute()throws IOException
    {
       Scanner infile = new Scanner(new FileReader("test.txt"));
      
       String fname,lname,name;
       double hoursworked,payrate,wages;
      
       fname = infile.next();
       lname = infile.next();
      
       hoursworked = infile.nextDouble();
       payrate = infile.nextDouble();
      
       wages = hoursworked * payrate;
       name = fname + " " + lname;
       System.out.println(name + " "+ wages);
    }
}