gpt4 book ai didi

java - 将控制台输出到文本文件中? - java

转载 作者:行者123 更新时间:2023-12-02 00:00:44 25 4
gpt4 key购买 nike

给定我的代码:

import java.util.Scanner;

public class AccountTest {

public static void main(String[] args) {
Account account1 = new Account(50.00);
Account account2 = new Account(0.00);

System.out.printf("account1 balance: $%.2f\n", account1.getBalance());
System.out.printf("account2 balance: $%.2f\n\n", account2.getBalance());

Scanner input = new Scanner(System.in);

System.out.print("Enter withdrawal amount for account1: ");

double withdrawalAmount = input.nextDouble();

System.out.printf("\nsubtracting %.2f from account1 balance\n",
withdrawalAmount);

account1.debit(withdrawalAmount);

System.out.printf("account1 balance: $%.2f\n", account1.getBalance());
System.out.printf("account2 balance: $%.2f\n\n", account2.getBalance());

System.out.print("Enter withdrawal amount for account2: ");
withdrawalAmount = input.nextDouble();
System.out.printf("\nsubtracting %.2f from account2 balance\n",
withdrawalAmount);
account2.debit(withdrawalAmount);

System.out.printf("account1 balance: $%.2f\n", account1.getBalance());
System.out.printf("account2 balance: $%.2f\n", account2.getBalance());
}
}

如何将“System.out.printf”转储到文件中(转储为不删除文件内容)?或者也许为每个实例创建单独的文件。初学者如有任何帮助,我们将不胜感激。谢谢。

最佳答案

1) 您可以在运行程序时将 stdout 重定向到文件

java AccountTest >> test.txt 

2)您可以在程序开始时重新分配标准输出

    PrintStream out = new PrintStream(new FileOutputStream("test.txt", true));
System.setOut(out);

3)你可以使用java.io.PrintWriter代替System.out

    PrintWriter out = new PrintWriter(new FileWriter("test.txt", true));
out.printf( "account1 balance: $%.2f\n", account1.getBalance() );

关于java - 将控制台输出到文本文件中? - java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14906458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com