这就是我要做的事情:
创建一个名为WriterDemo的TestFileWriter程序的新副本,该程序从用户获取输入并将其写入输出文件。程序应继续写行(循环可能有帮助),直到用户提供空行(无文本)作为输入。提示:一个具有终止条件的while循环依赖于来自用户的输入字符串是一个很好的起点......
应该从终端访问该程序,我无法确定在何处放置while循环而不会破坏程序。下面的代码是TestFileWriter的未修改版本。我不需要WriterDemo的完整代码,但只是关于如何使用它的一些建议。非常感谢帮助。
import java.io.FileReader;
import java.io.FileWriter;
public class WriterDemo {
public static void main(String args[]){;
FileWriter fout;
FileReader fin;
String str;
int k;
if(args.length==0){
System.out.println("Use an argument in the command line");
System.exit(0);
}
try{
fout = new FileWriter("WrittingProbe.txt");
for(int i=0; i<args.length; i++){
fout.write(args[i]);
fout.write(' ');
}
fout.close();
fin= new FileReader("WrittingProbe.txt");
System.out.println("The file content is:");
while((k=fin.read()) !=-1)
System.out.println((char)k);
System.out.println();
fin.close();
fout = new FileWriter("WrittingProbe.txt", true);
str="\nAdded Text\n";
fout.write(str);
fout.close();
fin = new FileReader("WrittingProbe.txt");
System.out.println("\nNow the file content is:");
while((k=fin.read()) != -1)
System.out.print((char)k);
System.out.println();
fin.close();
}
catch(Exception e){
System.out.println("Exception: " + e);
}
}
}
答案 0 :(得分:0)
Scanner scn = new Scanner(System.in);
ArrayList<String> list = new ArrayList<String>();
list.add(scn.nextLine());
for(;!list.get(list.size()-1).equals("");){ //Loops until the last input is a blank line
list.add(scn.nextLine());
//Or, you can do it here, as you go, if you want
}
//Or here, all at once, using the list
答案 1 :(得分:0)
try (FileWriter fileWriter = new FileWriter("G:\\test.txt")) {
Scanner scn = new Scanner(System.in);
while (true) {
String string = scn.nextLine();
if (string.equals("0")) {
break;
} else {
fileWriter.write(string+"\n");
}
}
}