helloo,


hello can you help me please i want to write to a file using bufferedwriter and bufferedreader but the problem is that i don't know how to use it i get an error please help me,hoping for your positive responds...

import java.io.*;
  import java.util.*;
  
  
  
  class Writefile
  {
  		
  		public static void main(String []args)throws Exception
  		{
  		
  		String name;
  
  		BufferedWriter bw = new BufferedWriter(new FileWriter(("write.txt")));
  		BufferedReader br = new BufferedReader(new BufferedWriter((System.in)));
  		
  		
  		System.out.println("Write a name");
  		name = br.readLine();
  		bw.write(name);
  		bw.close();
  		
  		
  	 }		
  		
  }

Recommended Answers

All 10 Replies

what error do you get ?

code line 17 is not correct:
BufferedReader br = new BufferedReader(new BufferedWriter((System.in)));
The argument should be a Writer object.

I have modified the program by Java source code example for your reference.
http://www.javadb.com/write-to-file-using-bufferedwriter
The data you typed in will be stored in myFile.txt
In one line type in "end" only to terminate the program.

import java.io.*;
import java.util.Scanner;

public class Main {
    
    /**
     * Type in some data to a file using a BufferedWriter via DOS
     */
    public void writeToFile() {
        
        BufferedWriter bufferedWriter = null;
        BufferedReader br=null;
        Scanner in = new Scanner(System.in);       
        try {            
          //Construct the BufferedWriter object
            bufferedWriter = new BufferedWriter(new FileWriter("MyFile.txt"));
            while(true){
            	String s = in.nextLine();
            	if (s.equals("end"))
            	break;
            	bufferedWriter.write(s);
            }     
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            //Close the BufferedWriter
            try {
                if (bufferedWriter != null) {
                    bufferedWriter.flush();
                    bufferedWriter.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    

    public static void main(String[] args) {
        new Main().writeToFile();
    }
}

code line 17 is not correct:
BufferedReader br = new BufferedReader(new BufferedWriter((System.in)));
The argument should be a Writer object.

I have modified the program by Java source code example for your reference.
http://www.javadb.com/write-to-file-using-bufferedwriter
The data you typed in will be stored in myFile.txt
In one line type in "end" only to terminate the program.

import java.io.*;
import java.util.Scanner;

public class Main {
    
    /**
     * Type in some data to a file using a BufferedWriter via DOS
     */
    public void writeToFile() {
        
        BufferedWriter bufferedWriter = null;
        BufferedReader br=null;
        Scanner in = new Scanner(System.in);       
        try {            
          //Construct the BufferedWriter object
            bufferedWriter = new BufferedWriter(new FileWriter("MyFile.txt"));
            while(true){
            	String s = in.nextLine();
            	if (s.equals("end"))
            	break;
            	bufferedWriter.write(s);
            }     
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            //Close the BufferedWriter
            try {
                if (bufferedWriter != null) {
                    bufferedWriter.flush();
                    bufferedWriter.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    

    public static void main(String[] args) {
        new Main().writeToFile();
    }
}

Hello sir tong1,


thank you for the reply i have problem on this it will not compile how do i run this program...i saved it Main.java

hoping for your postive responds...

it will not compile

What was the error?

It works in my machine. For example, you put the Main.java in the folder "forum"
Via DOS window do the following cammands:

E:\forum>javac Main.java

E:\forum>java Main
Hello everyone on the forum DaniWeb
end

so that a text file "MyFile.txt" is created where the "Hello everyone on the forum DaniWeb " is stored.

It works in my machine. For example, you put the Main.java in the folder "forum"
Via DOS window do the following cammands:

E:\forum>javac Main.java

E:\forum>java Main
Hello everyone on the forum DaniWeb
end

so that a text file "MyFile.txt" is created where the "Hello everyone on the forum DaniWeb " is stored.

hello,

thank you for the reply sir okay sir i will try this sir...i will write again if i have doubt....

code line 17 is not correct:
BufferedReader br = new BufferedReader(new BufferedWriter((System.in)));
The argument should be a Writer object.

I have modified the program by Java source code example for your reference.
http://www.javadb.com/write-to-file-using-bufferedwriter
The data you typed in will be stored in myFile.txt
In one line type in "end" only to terminate the program.

import java.io.*;
import java.util.Scanner;

public class Main {
    
    /**
     * Type in some data to a file using a BufferedWriter via DOS
     */
    public void writeToFile() {
        
        BufferedWriter bufferedWriter = null;
        BufferedReader br=null;
        Scanner in = new Scanner(System.in);       
        try {            
          //Construct the BufferedWriter object
            bufferedWriter = new BufferedWriter(new FileWriter("MyFile.txt"));
            while(true){
            	String s = in.nextLine();
            	if (s.equals("end"))
            	break;
            	bufferedWriter.write(s);
            }     
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            //Close the BufferedWriter
            try {
                if (bufferedWriter != null) {
                    bufferedWriter.flush();
                    bufferedWriter.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    

    public static void main(String[] args) {
        new Main().writeToFile();
    }
}

hello sir, here's my code and it works ,please correct me if i am wrong

hoping for your positive responds...

class Writefile
  {
  		
  		public static void main(String []args)throws Exception
  		{
	String name;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  		BufferedWriter bw = new BufferedWriter(new FileWriter("write.txt"));
  		
  		
  		
  		System.out.println("Write a name");
  		name = br.readLine();
  		bw.write(name);
  		bw.close();
  		
               }
 }

jemz, it works correctly. However, it works only for one line input. IOException would be more concrete/precise than Exception. I have modified your code so that client may type in several lines of strings. Type in "end" to finish typing.

import java.io.*;
class Writefile{		
  public static void main(String []args)throws IOException{
String name;
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	BufferedWriter bw = new BufferedWriter(new FileWriter("write.txt"));  	
	System.out.println("Write into the file write.txt. To finish typing input \"end\".");
	while(true){ 			//loop continues unless typing in the "end" line
	name = br.readLine(); 	// read each line of strings you typed in
	if (name.equals("end")) // check the content of input. If it is "end" 
	break;   				// then jump out of the while loop
	bw.write(name + (char)10); // Add the ASCII code 10 for the character new line
	}
	bw.close(); 		
     }
 }

It is not good to add the throws exception at the main method. Exception are meant to be caught and handled, not thrown at the main. Also the close needs to be in a finally. But if you try this:

try {
     BufferedWriter bw = new BufferedWriter(new FileWriter("write.txt"));
} catch (IOException ioe) {
     System.out.println(ioe.getMessage());
} finally {
    bw.close();
}

It will not compile because the BufferedWriter is declared in the try and it is not visible in the finally. So declare it outside the try, so it will be visible in the finally, and initialize it in the try.

You will also need an extra try, catch because bw.close() also throws an exception, so:

} finally {
    try {bw.close();} catch (Exception e) {/*you don't need anything here*/}
}
import java.io.*;
      class Writefile{

      public static void main(String []args) {
            // Declared here
            BufferedReader br = null;
            String name = null;
            BufferedWriter bw = null;
try {
      // Initialized here
      br = new BufferedReader(new InputStreamReader(System.in));
      bw = new BufferedWriter(new FileWriter("write.txt"));

      System.out.println("Write into the file write.txt. To finish typing input \"end\".");

      while(true){ //loop continues unless typing in the "end" line
        name = br.readLine(); // read each line of strings you typed in

        if (name.equals("end")) // check the content of input. If it is "end"
            break; // then jump out of the while loop
    
        bw.write(name);
        bw.newLine(); // for changing line when writing to a file.
      }

      bw.close();
} catch (IOException ioe) {
  System.out.println("Error: "+ioe.getMessage());
} finally {
    // finally start
    try {
      // the if is needed in case there is an exception above and bw never takes value
      if (bw!=null) bw.close(); 
    } catch (Exception e) {/*you don't need anything here*/}
    // finally end
}

      }

      }

Thank you, JavaAddict. The code you have modified above is definitely much better than previous code. I would like to put a comment on how to write a new line in a file.
My code:

bw.write(name + (char)10); // Add the ASCII code 10 for the character new line

works partially. After execution I have opened the output file “write.txt” via notepad where the new line character doesn’t work (it is shown as an unrecognized symbol). It works only in the case of opening the file by MS Word.
So one should use the way as JavaAddict writes:

bw.newLine(); // for changing line when writing to a file.
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.