我正在尝试学习java,但我不知道为什么我会遇到错误。我基本上想要的是用户将输入新字符并将被写入文件它不是"停止"(程序此时终止)。
你们能帮助我吗?
import java.io.*;
import java.util.*;
class FileHandling{
public static void main(String args[]){
System.out.println("Enter a File name");
Scanner input = new Scanner(System.in);
String file1Name = input.next();
if(file1Name == null){
return;
}
try{
File f1 = new File(file1Name+".txt");
f1.createNewFile();
String file1NameData = "";
String content = input.next();
FileWriter fileWritter = new FileWriter(f1.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
while(!(file1NameData=bufferWritter.readLine()).equalsIgnoreCase("stop")){
bufferWritter.write(file1NameData + System.getProperty("line.separator"));
}
bufferWritter.write(file1NameData);
bufferWritter.close();
}catch(Exception e){
System.out.println("Error : " );
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
你试图从作家那里读到你不能读的东西。您已经拥有扫描仪并使用它,您可以阅读表单系统输入,即键盘。
更改您的行:
这
while(!(file1NameData=bufferWritter.readLine()).equalsIgnoreCase("stop")){
要
while(!(file1NameData=input.nextLine()).equalsIgnoreCase("stop")){
答案 1 :(得分:0)
您正试图从输出中读取,而不是输入
while(!input.next().equalsIgnoreCase("stop")){
bufferWritter.write(file1NameData + System.getProperty("line.separator"));
}
答案 2 :(得分:0)
public static void main(String[] args) throws Exception {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File("test.txt"), true))) {
String line = null;
while ((line = reader.readLine()) != null) {
if (line.equals("stop"))
break;
writer.write(line);
writer.newLine();
}
}
}
}