Reputation: 255
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. What's causing this? Thanks in Advance NOTE: raj.txt exists in the mentioned directory...
Upvotes: 0
Views: 3494
Reputation: 3197
Use write method.
Put an end condition, such as s.equalsIgnoreCase("Exit")
Call method flush;
Try the following code.
while(!s.equalsIgnoreCase("Exit")){
pr.write(s);
pr.write("\n");
s=br.readLine();
}
pr.flush();
pr.close();
Upvotes: 0
Reputation: 68715
I don't think s
can ever be null
in your code. 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
Upvotes: 1