我对使用String输出的printWrttier有疑问,这是我的代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Out {
public static void main(String[] args) {
try {
File a=new File("C:/Users/Acer/Desktop/tyty.txt");
PrintWriter out=new PrintWriter(a);
Scanner c=new Scanner(System.in);
while(c.hasNextLine()) {
out.printf("%s",c.nextLine());
}
c.close();
out.close();
System.out.println("input written into file successfully!");
} catch(FileNotFoundException e) {
System.out.println("The file not found");
}
}
}
然而,当我在控制台中输入一些随机字符串如abcd时,它根本没有响应,我希望它打印出“输入成功写入文件!”,然后我可以看到我的输入显示在文本文件,但我的代码中哪个部分导致错误?
P.S ctrl + c在这里不起作用,因为它没有杀死循环。
答案 0 :(得分:1)
使用out.flush()刷新流,否则使用autoflush。见javadocs
http://docs.oracle.com/javase/6/docs/api/java/io/PrintWriter.html#PrintWriter(java.io.OutputStream,布尔值)
答案 1 :(得分:1)
while
循环退出时需要行尾终止符。在Windows上,这是Control-Z,对于* nix系统,Control-D
此外,匹配nextLine
与hasNextLine
while(c.hasNextLine()){
out.printf("%s",c.nextLine());
}
...您可能希望将这些close
语句移到finally
块中以防止try/catch
块中的任何异常
答案 2 :(得分:0)
引自Reimeus
while循环退出时需要行结束符。在Windows上,这是Control-C,对于* nix系统,Control-D
当您认为控制台中的输入已完成时,您必须按下以下按钮 1)Cntrl + C - 如果在Windows机器上运行 2)Cntrl + D - 如果在Linux(* nix)机器上运行
C:\Users\somone\Desktop>java Out
something
is
better
than
nothing
input written into file successfully!
我输入'nothing'后按'Cntrl + C'
答案 3 :(得分:0)
对于Eclipse,请使用“Ctrl + Z”。
最好添加System.out.println("Please Input the lines that needs to be written in the file \n ");
在While
语句