2014-12-11 2 views
0

저는 사용자가 자금을 예금하거나 인출 할 때 텍스트 파일의 잔액을 그에 맞게 업데이트해야하는 은행 시스템을 작성하고 있습니다.JAVA에서 텍스트 파일의 행을 어떻게 업데이트합니까?

 void saveFiles(int index) throws IOException{ 
     DateFormat dateFormat = new SimpleDateFormat("E MM/dd/yyyy hh:mm:ss a"); 
     Date date = new Date(); 

     BufferedWriter twriter = new BufferedWriter(new FileWriter("Transactions.txt", true)); 
     BufferedWriter fwriter = new BufferedWriter(new FileWriter("Customers.txt", true)); 

     PrintWriter outputFile = new PrintWriter(fwriter); 
     PrintWriter output = new PrintWriter(twriter); 

     //update to Customer.txt file 
     outputFile.println(people[index].getCustID() + "," +people[index].getTitle() + "," +people[index].getfName() + ","+people[index].getlName()+ "," 
     +people[index].getUsername() + "," +people[index].getPassword() + ","+people[index].getSSN() + ","+people[index].getUniqueID() + "," 
     +people[index].getSightkey() + ","+ FCA + "," + TSA + "," + people[index].getSoarAcctBal()); 

     //update Transactions.txt file 
     output.write((dateFormat.format(date) + "," +people[index].getCustID() + "," +numbers[index].getCheckingAcctNum() + "," + transferAmount + "," + "Withdraw" + "," + people[index].getSoarAcctBal())); 

     outputFile.flush(); 
     outputFile.close(); 
     output.flush(); 
     output.close();  
     } 

고객 파일

 //DEFAULT CONSTRUCTOR 
     public GEBank() { 
      people = new Customer[4]; 
     } 

    //LOAD CUSTOMERS FILE 
    void loadCustomers() throws IOException, FileNotFoundException, ParseException{ 
     BufferedReader inputFile = new BufferedReader(new FileReader("Customers.txt")); 
     //String that holds current file line. 
     String custID = "", title = "", fName = "", lName = "", username = "", password = "", SSN = "", uniqueID = "", sightkey = "", 
       checkingAcctBal = "", savingsAcctBal = "", soarAcctBal = "", line = ""; 

     //Line number of count 
     int i = 0; 

     //Read the first customer 
     line = inputFile.readLine(); 

     //load the array 
     while (line != null) 
     { //Get each item from the line, stopping at the comma separator 
      StringTokenizer st = new StringTokenizer(line,","); 

      //Get each token and store it in the array 
      custID = st.nextToken(); 
      title = st.nextToken(); 
      fName = st.nextToken(); 
      lName = st.nextToken(); 
      username = st.nextToken(); 
      password = st.nextToken(); 
      SSN = st.nextToken(); 
      uniqueID = st.nextToken(); 
      sightkey = st.nextToken(); 
      checkingAcctBal = st.nextToken(); 
      savingsAcctBal = st.nextToken(); 
      soarAcctBal = st.nextToken(); 

      //Instantiate each customer 
      people[i] = new Customer(Integer.parseInt(custID), title, fName, lName, username, password, 
        Integer.parseInt(SSN), uniqueID, sightkey, Float.parseFloat(checkingAcctBal), Float.parseFloat(savingsAcctBal), Float.parseFloat(soarAcctBal)); 

      //Get the next customer 
      i++; 
      //System.out.println(username); 
      //Read the next customer 
      line = inputFile.readLine(); 

     } 
      inputFile.close(); 
      //System.out.println("The Customer Info file is loaded."); 
    } 

이 내 transferFunds 방법입니다로드. 나는 새로운 균형을 설정하고 파일에 설정된 균형을 쓸 수 있다고 생각했지만, 제대로 작동하지 않아서 잘못했을 수도 있습니다.

//TRANSFER FUNDS METHOD 
    void transferFunds(int index) throws IOException{ 
     BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); 

     DateFormat dateFormat = new SimpleDateFormat("E MM/dd/yyyy hh:mm:ss a"); 
     Date date = new Date(); 

     int transferchoice = -1; 

     do{ 
     System.out.println("\n-- TRANSFER FUNDS MENU --\n"); 
     //transfer from checking to savings 
     System.out.println("1: Checking Account to Savings Account"); 
     //transfer from savings to checking 
     System.out.println("2: Savings Account to Checking Account"); 

     System.out.println("\nMake a selection from the above menu options: "); 
     transferchoice = Integer.parseInt(input.readLine()); 

     //show account numbers of customer 
     System.out.println("\n-- ACCOUNT NUMBERS --\n"); 
     System.out.println("Checking Account Number: "+numbers[index].getCheckingAcctNum());   
     System.out.println("Savings Account Number: "+numbers[index].getSavingsAcctNum()); 
     //show account balances of customer 
     System.out.println("\n-- CURRENT BALANCE --\n"); 
     System.out.println("Checking Account Balance: $"+people[index].getCheckingAcctBal()+".");  
     System.out.println("Savings Account Balance: $"+people[index].getSavingsAcctBal()+"."); 

     System.out.println("\nHow much would you like to transfer?"); 
     transferAmount = Float.parseFloat(input.readLine()); 

     System.out.println("\nBusiness Date & Time: " + dateFormat.format(date)); 

     //FROM CHECKING TO SAVINGS ACCOUNT 
     FCA = (people[index].getCheckingAcctBal() - transferAmount); 
     TSA = (people[index].getSavingsAcctBal() + transferAmount); 

     //FROM SAVINGS TO CHECKING ACCOUNT 
     FSA = (people[index].getSavingsAcctBal() - transferAmount); 
     TCA = (people[index].getCheckingAcctBal() + transferAmount); 

     saveFiles(index); 

     if(transferchoice == 1){ 
      System.out.println("\nYou've chosen to transfer $" +transferAmount+ " from your Checking Account to your Savings Account.\n" 
        + "\n-- UPDATED BALANCE --\n" 
        + "\nChecking Account Balance: $"+FCA+//money[index].setCheckingAcctBal(FCA) 
        "\nSavings Account Balance: $"+TSA+"" 
        + "\nFunds successfully transferred"); //confirm the transaction 

     }else if(transferchoice == 2){ 
      System.out.println("\nYou've chosen to transfer $" +transferAmount+ " from your Savings Account to your Checking Account.\n" 
        + "\n-- UPDATED BALANCE --\n" 
        + "\nChecking Account Balance: $"+FSA+ 
        "\nSavings Account Balance: $"+TCA+"" 
        + "\nFunds successfully transferred"); //confirm the transaction 

     } 
      if(people[index].getCheckingAcctBal() < transferAmount && people[index].getSavingsAcctBal() < transferAmount){ 
       System.out.println("We're sorry, you do not have sufficient funds to complete this transaction. Transaction Cancelled.\n\n"); 
       return; 
      } 
      //Ask customer if they would like to view another balance 
      System.out.print("\nDo you want to make another transfer? [Enter y/n]: "); 
      moretransfers = input.readLine().charAt(0); 
      }while (moretransfers == 'Y' || moretransfers == 'y'); 
      //If moretransfers is no, then show displayLoginMenu method 
      if (moretransfers == 'N' || moretransfers == 'n') 
      { displayLoginMenu(index);} 
    } 

다음은 사용자가 한 계정에서 다른 계정으로 $ 400.00를 이체 한 후 추가 한 텍스트 파일입니다. 그것은 마지막 줄을 만들고 있습니다. 내가하고 싶은 무슨 "사람들 [인덱스]"이 줄을 찾은 다음

100,Ms,Jane,Doe,10ann,guy,1234,brunch,yellow,20000.00,5000.00,2000.00 
101,Mr,John,Smith,1mark,girl,2345,lunch,gray,10000.00,3000.00,6000.00 
102,Ms,Jenaya,Joseph,2jjPM,jj2,6789,breakfast,green,40000.00,20000.00,80000.00 
103,Mr,Edward,Donkor,05001,1005,5432,dinner,blue,25000.00,7100.00,8000.00 

101,Mr,John,Smith,1mark,girl,2345,lunch,gray,9600.0,3400.0,6000.0 

사람이 도와 드릴 업데이트 된 출력으로 대체하는 것입니다? 나는 연구를 해왔고 임시 파일을 만든 다음 정보를 새 파일로 덮어 쓸 수 있음을 알았습니다. 그러나 나는 이것을 정확하게하는 방법에 관해 아직도 확신이 없다. 저는 아직 Java에 익숙하지 않으므로 도움이 될 것입니다.

+0

파일 인라인을 절대로 변경하지 마십시오!수정 된 내용을 새 파일에 쓴 다음 이전 이름으로 바꿉니다. 또한 은행원 인 경우 고객이 실제로 'float'을 사용하여 감사하지 않을 것입니다 : p – fge

+0

이전 파일의 내용에 신경 쓰지 않는다고 가정하면 고객 배열의 모든 데이터를 수정해야합니다. 업데이트가 필요하다면 배열을 쉼표로 구분 된 텍스트 행으로 변환하는 구문 분석기를 만들어이를 사용하여 이전 파일을 새 데이터로 덮어 씁니다. – Scherling

+0

또한 ArrayList로 사람들 배열을 교환하십시오. 파일에 다른 행을 추가하면 코드가 – Scherling

답변

2

어떻게 JAVA의 텍스트 파일에서 행을 업데이트합니까?

그렇지 않습니다.

Java, C, C#, Python이 아니고 Ruby가 아니라 Perl이 아니라 Brainfuck이 아닙니다. 모든 언어가 아님. 텍스트 파일 인라인을 수정

당신이 일이 될 것입니다 무엇을 말할 수있는 확실한 보장하지만, (100 - 엡실론)에 엡실론은 매우 0에 가까운 인과 함께 %의 경우, 당신은 을 잃게됩니다 적어도 파일의 원래 내용

새 파일에 수정 된 내용을 쓰고 원자 이름을 이전 이름으로 바꿉니다. 운이 좋으면, java.nio.file은 StandardCopyOption.ATOMIC_MOVE입니다.

는 (당신은 아직도의 mmap() FileChannel.map()와 비록 파일, 수 있지만 이것은 단지 일반적으로 고정 된 크기 레코드와 파일에서 수행되며, 같은 텍스트 파일이 아닌 같은 문자를 판명 할 수있는 상기시킨다. 사용하는 인코딩에 따라 2 바이트 이상이 필요합니다.)

+0

어, 정말로 아닙니다. [pascal] (http://en.wikipedia.org/wiki/Pascal_%28programming_language%29)에서 작동합니다. – Unihedron

+0

@ Mr.777 예, 그런 언어가 실제로 존재합니다 – fge

-1

도움이된다면 이것을 볼 수 있습니다. 읽기 쉬운.

public class ExampleTextEdit { 

public static String APPLICATION_LOCATION; 
public static File textFile; 
public static BufferedReader reader; 

public static void main(String[] args) { 
    APPLICATION_LOCATION = ExampleTextEdit.class.getProtectionDomain() 
      .getCodeSource().getLocation().getPath(); 
    textFile = new File(APPLICATION_LOCATION + File.separator 
      + "mytextfile.txt"); 
    try { 
     if (!textFile.exists()) { 

      textFile.createNewFile(); 
      BufferedWriter writer = new BufferedWriter(new FileWriter(
        textFile)); 
      for (int i = 0; i < 20; i++) { 
       writer.write("this that " + i); 
       writer.newLine(); 
      } 
      writer.flush(); 
      writer.close(); 

     } else { 
      loadText(); 
      File f = new File(APPLICATION_LOCATION + File.separator + "temp.txt"); 
      f.createNewFile(); 
      String temp; 
      BufferedWriter writeNew = new BufferedWriter(new FileWriter(f)); 
      reader = new BufferedReader(new FileReader(textFile)); 
      while ((temp = reader.readLine()) != null) { 
       if (temp.contains("" + 14)) 
        writeNew.write("lol changed"); 
       else 
        writeNew.write(temp); 
       writeNew.newLine(); 
      } 
      writeNew.flush(); 
      writeNew.close(); 
      reader.close(); 
      textFile.delete(); 
      f.renameTo(textFile); 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

public static void loadText() throws Exception { 
    String line; 
    reader = new BufferedReader(new FileReader(textFile)); 
    while ((line = reader.readLine()) != null) { 
     System.out.println(line); 
    } 
} 

} 

라이브러리에 익숙해지기 전에는 그다지 잘 생각하지 않아도됩니다.

+0

왜 특정 예외 대신에 '예외'를 ​​던집니까?! – Unihedron

+0

어쨌든 stacktrace를 읽을 수 있기 때문입니다. Stacktrace를 읽고 어떤 예외인지 이해하지 못하면 문제가 발생합니다 ... –

+0

'throws' 선언에'Exception '을 위임하는 이유가 아닙니다. [이와 같이 작성된 메소드는 일반적으로 유지할 수 없습니다.] (https://www.thc.org/root/phun/unmaintain.html) 그러면 ThreadDeath가 잘못 잡히는 등 더 많은 문제를 일으킬 수 있습니다. 편의는 적절한 코드를 대신 할 수 없습니다. – Unihedron

-1

나는 그것을 알아낼지도 모른다.

 void saveFiles(int index) throws IOException{ 

     BufferedReader br = new BufferedReader(new FileReader(new File("Customers.txt"))); 
     String uname = people[index].getUsername(); 
     String line = null; 
     StringBuilder sb =new StringBuilder(); 
     while ((line = br.readLine())!=null) 
     { 
      if(line.indexOf(uname)!=-1) 
      { 
       //do your logic here 
       sb.append(people[index].getCustID() + "," +people[index].getTitle() + "," +people[index].getfName() + ","+people[index].getlName()+ "," 
         +people[index].getUsername() + "," +people[index].getPassword() + ","+people[index].getSSN() + ","+people[index].getUniqueID() + "," 
         +people[index].getSightkey() + ","+ FCA + "," + TSA + "," + people[index].getSoarAcctBal() +"\n"); 
      }else{ 
       sb.append(line+"\n"); 
      } 
     } 
     br.close(); 
     BufferedWriter bw = new BufferedWriter(new FileWriter(new File("Customers.txt"))); 
     PrintWriter out = new PrintWriter(bw); 
     out.print(sb.toString()); 
     out.flush(); 
     out.close(); 
     } 

하지만 내 출력은 지금과 같다 :

100,Ms,Jane,Doe,10ann,guy,1234,brunch,yellow,20000.00,5000.00,2000.00101,Mr,John,Smith,1mark,girl,2345,lunch,gray,9600.0,3400.0,6000.0102,Ms,Jenaya,Joseph,2jjPM,jj2,6789,breakfast,green,40000.00,20000.00,80000.00103,Mr,Edward,Donkor,05001,1005,5432,dinner,blue,25000.00,7100.00,8000.00 

어떻게 새로운 라인에 각 인스턴스를 인쇄 할 수 있습니까?

관련 문제