如何使用java替换文本文件中的字符串? [英] How to replace string in textfile using java?

查看:93
本文介绍了如何使用java替换文本文件中的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码,如果记录与我的输入匹配,我的问题就是替换文本文件中的字符串.试着运行我的程序,我的操作系统是 Ubuntu.

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();
}

}

推荐答案

你可以轻松做到以下

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));

或在 Java 7 或更新版本中

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

这篇关于如何使用java替换文本文件中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆