如何从JAVA中的文本文件更新一行?

时间:2014-12-11 16:04:02

标签: java arrays append text-files overwrite

我正在编写一个银行系统,当用户存入或取出资金时,文本文件中的余额应相应更新。

        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从一个帐户转移到另一个帐户后的附加文本文件。它创造了最后一行。我想要它做的是找到这条线&#34;人[索引]&#34;然后用更新的输出

替换它
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新手,所以任何帮助都会受到赞赏。

3 个答案:

答案 0 :(得分:2)

  

如何从JAVA中的文本文件更新一行?

你没有。

不是Java,不是C语言,不是C#,不是Python,不是Ruby,不是perl,不是Brainfuck。不是任何语言。

内联修改文本文件是一个万无一失的保证,您无法告诉将要发生的事情,但在(100 - epsilon)%的情况下,epsilon 非常接近0 ,你将至少丢失文件的原始内容

将修改后的内容写入新文件,然后以原子方式重命名为旧文件。幸运的是,java.nio.file为你提供了StandardCopyOption.ATOMIC_MOVE

(你仍然可以使用FileChannel.map() mmap()文件;但这通常只对具有固定大小记录的文件进行;这不是文本文件。提醒根据您使用的编码,相同的字符可能会超过一个字节。)

答案 1 :(得分:-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);
    }
}

}

你不需要太过花哨的东西,直到你更熟悉图书馆坚持你所知道的东西。

答案 2 :(得分:-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

如何将每个实例打印到新行?