[英]How to write in a file from keyboard input in java?
I wrote a program to write in a file... 我写了一个程序来写文件...
package iofile;
import java.io.*;
public class WriteFile {
public static void main(String[] args) {
String s;
File file=new File("C:\\Users\\Rajesh\\oacert\\Learn\\src\\iofile\\raj.txt");
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
try{
PrintWriter pr=new PrintWriter(new BufferedWriter(new FileWriter(file,true)));
System.out.println("enter to write in a file...");
s=br.readLine();
while(s!=null){
pr.println(s);
s=br.readLine();
}
pr.close();
}
catch(Exception e){
}
}
}
But it's unable to write anything in raj.txt. 但是它无法在raj.txt中写入任何内容。 What's causing this?
是什么原因造成的? Thanks in Advance NOTE: raj.txt exists in the mentioned directory...
在此先感谢您注意:raj.txt存在于上述目录中...
I don't think s
can ever be null
in your code. 我认为
s
在您的代码中永远不可能为null
。 You should better use a terminating string to exit the program. 您最好使用终止字符串退出程序。 Try replacing this:
尝试替换此:
while(s!=null){
with 同
while(!s.equals("exit")){
and enter 'exit' to terminate the loop 并输入“退出”以终止循环
Use write method. 使用写方法。
Put an end condition, such as s.equalsIgnoreCase("Exit") 放置一个结束条件,例如s.equalsIgnoreCase(“ Exit”)
Call method flush; 调用方法flush;
Try the following code. 请尝试以下代码。
while(!s.equalsIgnoreCase("Exit")){ while(!s.equalsIgnoreCase(“ Exit”)){
pr.write(s);
pr.write("\n");
s=br.readLine();
}
pr.flush();
pr.close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.