Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/379.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在JAVA中更新文本文件中的行?_Java_Arrays_Append_Text Files_Overwrite - Fatal编程技术网

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

如何在JAVA中更新文本文件中的行?,java,arrays,append,text-files,overwrite,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 Buffere

我正在编写一个银行系统,当用户存款或取款时,文本文件中的余额应该相应地更新

        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.");
    }
这是我的转账方式。我想我可以设置新的平衡,并将该平衡写入文件,但它不起作用,我可能做错了

//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);}
    }
有人能帮忙吗?我一直在研究,我发现您可以创建一个临时文件,然后将信息覆盖到一个新文件中。但我仍然不确定到底该怎么做。我对Java还是新手,所以如果有任何帮助,我将不胜感激

如何在JAVA中更新文本文件中的行

你没有

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

内联修改文本文件是一个肯定的保证,您无法判断将发生什么,但是在100-epsilon%的情况下,epsilon非常接近于0,您至少会丢失文件的原始内容

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


您仍然可以使用FileChannel.map映射文件;但这通常只在具有固定大小记录的文件上进行;这不是一个文本文件。提醒您,根据您使用的编码方式,同一个字符可能会变成多个字节。

如果有帮助,您可以查看这个。容易阅读

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

}

在你对图书馆更加熟悉之前,你不必对这些东西太着迷,只要坚持你所知道的

我可能已经弄明白了

        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

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

切勿内联修改文件!将修改后的内容写入新文件,然后重命名为旧文件。此外,如果你是一名银行家,你的客户真的不会感谢你使用浮点数:如果你不关心旧文件的内容,你只需修改客户数组中需要更新的任何数据,然后制作一个解析器,将数组转换为逗号分隔的文本行,并使用它用新数据覆盖旧文件。另外,用ArrayList替换人员数组。如果您在文件中添加了另一行,您的代码breaks@Scherling好啊这会更新我想要更改的行,然后重写未更改的行?然后删除旧文件并使用更新的数据创建新文件?你能给我举个例子吗?过去几天我一直在尝试,但我一直遇到困难。你可以让你的类可以序列化,而不是让这个文件不存在。呃,不是真的。它在.@Mr.777中工作是的,这样的语言实际上存在。为什么要抛出异常而不是特定异常?!因为我无论如何都可以读取堆栈跟踪。如果您阅读了stacktrace,但不了解它是哪一个异常,那么您就有问题了……这并不是委派抛出声明来接受异常的理由。而且你会造成更多的麻烦,比如ThreadDeath被错误地捕获。方便并不能代替正确的代码。
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