Kean Allen
Kean Allen

Reputation: 31

How to replace string in textfile using java?

Here's my code, my problem is all about replacing string in textfile if the record is match with my input. just try to run my program, my OS is Ubuntu.

package atm_bankmanagement;
import java.util.Scanner;
import java.io.*;
public class ATM_BankManagement {

// create a main menu

public static void MainMenu()
{
System.out.println("[1] Admin");
System.out.println("[2] User");
System.out.println("[3] Exit");

Scanner a = new Scanner(System.in);
int mainChoice=a.nextInt();
switch(mainChoice)
{
case 1: AdminPanel();
break;
case 2: UserPanel();
break;
        case 3:
            break;
}
}
// END OF MainMenu method

// create a method for admin panel

public static void AdminPanel()
{
    System.out.print("Enter password: ");
    Scanner sc = new Scanner(System.in);
    int pass = sc.nextInt();
    if ((pass==132748))
    {
    System.out.println("---ADMIN PANEL---");
    System.out.println("[1] Add Bank Account");
    System.out.println("[2] Add Deposit");
    System.out.println("[3] Exit");

    Scanner b = new Scanner(System.in);
    int adminPanelChoice=b.nextInt();
    switch(adminPanelChoice)
    {
        case 1: APaddbankaccount();
            break;
        case 2: APadddeposit();
            break;
        case 3: MainMenu();
            break;
    }
    }
    else
    {
        System.out.println("Invalid password!");
        MainMenu();
    }

}
// END OF AdminPanel method

// create a method for admin panel add bank account

public static void APaddbankaccount()
{
    System.out.println("---ADMIN PANEL---");
    System.out.println("--Add Bank Account--");
    System.out.print("Enter Account Name: ");
    Scanner c = new Scanner(System.in);
    String accname = c.nextLine();
    System.out.print("Enter Account Number: ");
    Scanner d = new Scanner(System.in);
    int accnum = d.nextInt();
    System.out.print("Enter Amount: ");
    Scanner f = new Scanner(System.in);
    int amount=f.nextInt();


    try
    {
       File fi = new File("/home/kean/insert.txt") ;
       BufferedWriter w = new BufferedWriter(new FileWriter(fi,true));
       w.write(accnum+";"+accname+";"+amount);
       w.newLine();

       System.out.println("[1] Save Entry");
       System.out.println("[2] Exit");

       Scanner g = new Scanner(System.in);
       int addbankaccountChoice=g.nextInt();
       switch(addbankaccountChoice)
       {
           case 1: w.flush(); w.close();System.out.println("Saved...");MainMenu();
               break;
           case 2: MainMenu();
       }
    }
    catch(IOException e)
    {

    }

}
// END OF APaddbankaccount

// create a method for Admin Panel Add Deposit

public static void APadddeposit()
{
    System.out.println("---ADMIN PANEL---");
    System.out.println("--Add Deposit--");
    System.out.print("Enter account number:");
    Scanner h = new Scanner(System.in);
    String con = h.next();

    int pin = Integer.parseInt(con);

   try
   {

       BufferedReader br = new BufferedReader(new FileReader("/home/kean/insert.txt"));
       String mysplit="";


      String arr[] = new String[mysplit.split(";").length];
     String acname="";


      for(int i=0;i<arr.length;i++)
      {
           while((mysplit=br.readLine())!=null)
      {
          arr=mysplit.split(";"); 
          if((arr[i]).equals(con))
          {
              String accountName = arr[1];

              acname = accountName;
              System.out.println("Account Name: "+acname);

          }

      }
      }
      System.out.print("Enter Amount to be deposited: ");
      Scanner j = new Scanner(System.in);
      String depAmount=j.next();

      arr[2]=depAmount;
      System.out.print("Date: ");
      Scanner k = new Scanner(System.in);
      String dt = k.nextLine();

      File fil = new File("/home/kean/deposit.txt");
      BufferedWriter bw = new BufferedWriter(new FileWriter(fil,true));


      bw.write(con+";"+acname+";"+depAmount+";"+dt);
      bw.newLine();


      System.out.println("[1] Save Entry");
      System.out.println("[2] Cancel");
      Scanner l = new Scanner(System.in);
      int depChoice=l.nextInt();
      switch(depChoice)
      {
          case 1: bw.flush(); bw.close(); System.out.println("Saved...");MainMenu();
              break;
          case 2: MainMenu();
              break;
      }

   }
   catch(IOException e)
   {

   }

}
// END OF APadddeposit method

//<!--------C-O-D-E--H-A-R-D---------!>

// create a method for user account

public static void UserPanel()
{
    System.out.println("---USER PANEL---");

    System.out.print("Enter PIN: ");
    Scanner m = new Scanner(System.in);
    String myPin = m.next();



    try
    {
          BufferedReader br = new BufferedReader(new FileReader("/home/kean/insert.txt"));
       String mysplit="";

      String arr[] = new String[mysplit.split(";").length];
        String myname="";


         BufferedReader nbr = new BufferedReader(new FileReader("/home/kean/deposit.txt"));
       String nmysplit="";

       String myarr[] = new String[nmysplit.split(";").length];


      for(int i=0;i<myarr.length;i++)
      {
           while((mysplit=br.readLine())!=null && (nmysplit=nbr.readLine())!=null)
      {

          arr=mysplit.split(";"); 
          myarr=nmysplit.split(";");
          if((myarr[i]).equals(myPin) && (arr[i]).equals(myPin))
          {


              String accounName = arr[1];
              String money1 = arr[2];
              String money2= myarr[2];
              int mon = Integer.parseInt(money1);
              int monn = Integer.parseInt(money2);
              int totalmoney = mon+monn;

              myname = accounName;

               File myFi = new File("/home/kean/balance.txt");
              BufferedWriter wri = new BufferedWriter(new FileWriter(myFi,true));


              wri.newLine();
              wri.flush();

      System.out.println("Hi "+accounName+" what do you want to do?");
      System.out.println("[1] Balance Inquiry");
      System.out.println("[2] Withdraw");
      System.out.println("[3] Exit");
      Scanner n = new Scanner(System.in);
      int usersChoice=n.nextInt();
      switch(usersChoice)
      {
          case 1: 
              System.out.println("Your Current Balance is " +totalmoney);wri.close();

    MainMenu();
              break;
          case 2:  System.out.println("Your Current Balance is " +totalmoney);
                    System.out.println("Enter amount to be withdraw: ");
                    Scanner o = new Scanner(System.in);
              int wdrw = o.nextInt();
              if(wdrw>25000)
              {
                  System.out.println("Sorry you can't withdraw an amount higher than 25000");
                  UserPanel();
              }
          else
              {
                  File Note = new File("/home/kean/wihdraw.txt");
                  BufferedWriter wrt = new BufferedWriter(new FileWriter(Note));

                  wrt.write(myPin+";"+accounName+";"+wdrw);
                  wrt.newLine();
                  wrt.flush();
                  wrt.close();
                  int remain = totalmoney-wdrw;
                  System.out.println("Your remaining balance is "+remain);
                  MainMenu();
              }
            break;
      }

          }

      }
      }


    }
    catch(IOException e)
    {

    }
}

// END OF UserPanel's method

public static void main(String[] args) 
{
    MainMenu();
}

}

Upvotes: 0

Views: 437

Answers (1)

Manu Zi
Manu Zi

Reputation: 2370

You can easily do the following

Path path = Paths.get("home/kean/insert.txt");
Charset charset = StandardCharsets.UTF_8;

String content = new String(Files.readAllBytes(path), charset);
content = content.replaceAll("foo", "bar");
Files.write(path, content.getBytes(charset));

or in Java 7 or newer

String content = IOUtils.toString(new FileInputStream(myfile), myencoding);
content = content.replaceAll(myPattern, myReplacement);
IOUtils.write(content, new FileOutputStream(myfile), myencoding);

But please take notice, you need to add a error handling and you must close the streams.

IOUtils: http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/IOUtils.html

Upvotes: 1

Related Questions