鉴于我的代码:
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”转储到文件中(转储为不删除文件的内容)?或者可能为每个实例创建单独的文件。任何帮助在这里是初学者。感谢。
答案 0 :(得分:2)
1)您可以在运行程序时将stdout重定向到文件
java AccountTest >> test.txt
2)你可以在程序开头重新分配stdout
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() );
答案 1 :(得分:1)
这取决于您运行此程序的方式。如果手头有POSIX shell,只需将其标准输出重定向到文件即可。
以下内容将附加到日志文件中:
$ java -jar myjar.jar >> log
每次都会创建一个新的epoch日期日志文件($(…)
可能是特定于bash的功能,我不确定):
$ java -jar myjar.jar > log-$(date +%s)