我需要编写一个Java程序,将控制台中输入的信息写入.txt文件。如果.txt文件已经存在,则必须打开它并在另一行上写入附加信息。如果新的“Lifter”不存在.txt文件,它将创建.txt并将其写入。基本上我不知道如何为输入的每个名称创建新的.txt以及如何编辑它person的.txt已经存在。我该怎么做呢?
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import java.util.Scanner;
public class MeetPrinter {
public static void getInfo() {
Scanner scanner = new Scanner(System.in);
int question;
String firstName;
String lastName;
int squat;
int bench;
int lift;
String meetName;
do {
System.out.println("Enter first name: ");
firstName = scanner.next();
System.out.println("Enter Last Name: ");
lastName = scanner.next();
System.out.println("Enter new Meet Name: ");
meetName = scanner.next();
System.out.println("Enter max squat weight in kg: ");
squat = scanner.nextInt();
System.out.println("Enter max bench press in kg: ");
bench = scanner.nextInt();
System.out.println("Enter max deadlift in kg: ");
lift = scanner.nextInt();
System.out
.println("Enter '1' to enter more lifters or '2' if you are done entering.");
question = scanner.nextInt();
} while (question == 1);
try{
PrintWriter out = new PrintWriter("output.txt");
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(100000);
out.println(lastName + ", " + firstName + " Record #: " + randomInt);
out.println("");
String meet = "Meet Name";
String sq = "SQ Max";
String bp = "BP Max";
String sub = "SUB Total";
String dl = "DL Max";
String tot = "Total";
out.printf("%20s %15s %18s %19s %18s %18s",meet ,sq,bp,sub,dl,tot);
out.println("");
out.printf("%20s", meetName);
out.printf("%10d (%6.2f)", squat, squat * 2.2);
out.printf("%10d (%6.2f)", bench, bench * 2.2);
float subPounds = (float) ((float)(squat + bench) * 2.2);
out.printf("%10d (%6.2f)", squat + bench, subPounds);
out.printf("%10d (%6.2f)", lift, lift * 2.2);
float tPounds = (float) ((float)(squat + bench + lift) * 2.2);
out.printf("%10d (%6.2f)", squat + bench + lift, tPounds);
out.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
答案 0 :(得分:2)
<强>更新强>
变化
PrintWriter out = new PrintWriter("output.txt");
到
FileWriter out = new FileWriter("output.txt", true);
如果文件存在,true
将告诉FileWriter附加到文件,这正是您想要做的。
这是FileWriter的javadoc。
FileWriter可以选择编写字符串,这就是你所做的。
也像twain249建议的那样,对路径做点什么......
答案 1 :(得分:1)
Java文件操作
File file = new File("<file name>");
BufferedWriter writer = null;
if(file.exists()){ //Check existence check
writer = new BufferedWriter(new FileWriter(toFile,true));
//bytes will be written to the end of the file rather than the beginning
}else{
file.createNewFile() //creating new file
writer = new BufferedWriter(new FileWriter(toFile));
}
BufferedWriter writer = new BufferedWriter(writer);
writer.write(...);
---or----
PrintWriter out
= new PrintWriter(new BufferedWriter(writer));
out.println(...);
答案 2 :(得分:0)
您应该使用FileWriter。 API:http://docs.oracle.com/javase/1.4.2/docs/api/java/io/FileWriter.html 示例:http://www.roseindia.net/java/beginners/java-write-to-file.shtml
有条件的例子:google'写入文件java示例'