我的程序的目标是让用户有机会在新文件或旧文件中添加内容。
由于我的代码,用户只能向文件添加一个单词。 我写下了问题所在。 我不知道如何使文件中单词的保存不受限制。 我尝试使用for循环...不幸的是,这没有任何意义。
public class AddAndSave {
private static Scanner scanner = new Scanner(System.in);
private static Formatter formatter = null;
private static Scanner reader;
public static void main(String args[]) {
System.out.println("In which file do you want to add?");
String fileName = scanner.next();
File myFile = new File("C://Meine Dateien// " + fileName + ".txt");
if (myFile.exists() == true) {
try {
reader = new Scanner(myFile);
String fileContent = "";
while (reader.hasNext() == true) {
fileContent = fileContent + reader.next();
}
formatter = new Formatter(myFile);
formatter.format("%s", fileContent + " ");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
try {
formatter = new Formatter(myFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("What do you want to add?");
String newInput = scanner.next();//hier is the problem
formatter.format("%s", newInput);
System.out.println();
System.out.println("Finish! Thank you for using our programm!");
formatter.close();
}
}
您的问题是您使用了错误的 Scanner 方法从文件和用户中检索字符串行数据。
使用 Scanner#nextLine() 方法代替 Scanner#next() 方法,并在while循环条件中将其与 Scanner#HasNextLine() 方法结合使用(而不是 Scanner#hasNext() 方法):
String newInput = scanner.nextLine();
使用Scanner#nextLine()方法,提示您输入文件名并提示要添加到文件的内容!也可以在while循环中使用它来读取文件(与Scanner#hasNextLine()方法结合使用)。仔细阅读所有这些方法之间的区别!
Scanner#hasNext() 和 Scanner#next() 方法更适合基于单词 Token (word) 的情况(一次一个单词),而Scanner#hasNextLine() 和Scanner#nextLine()方法用于整个字符串行。这才是我相信你真正想要的。
其他注意事项:
您可能希望删除最后一个正斜杠 (//) 之后的空格:
"C://Meine Dateien// " + fileName + ".txt";
当然,除非您希望 t0 在应用程序创建的每个文件的每个名称的开头添加一个空格。
在诸如if语句之类的条件下使用布尔变量时,您可以只使用:
if (myFile.exists()) { // IF true
而不是:
if (myFile.exists() == true) { // IF true
和:
if (!myFile.exists()) { // IF false
而不是:
if (myFile.exists() == false) { // IF false
无论哪种方式都很好,但你以后会发现较短的方式不太容易因错别字而出错,我认为它更容易阅读,但这只是我的意见。
不要忘记关闭文件阅读器。使用"尝试使用资源"来为您的读者和作者处理此类事情。