ankitaloveroses
ankitaloveroses

Reputation: 17

Writing to a file in Java. Help me code

I am passing a file path to this method which writes the in txt file. But when I run this program it is not writing full and I don't know where I made mistake.

public void content(String s) {
  try { 
    BufferedReader br=new BufferedReader(new FileReader(s)); 
    try {
      String read=s;
      while((read = br.readLine()) != null) {    
        PrintWriter out = new PrintWriter(new FileWriter("e:\\OP.txt"));
        out.write(read);
        out.close();
      }
    } catch(Exception e) { }    
  } catch(Exception e) { }
}

Upvotes: 1

Views: 171

Answers (5)

Brijesh
Brijesh

Reputation: 301

Your closing stream before finishing it. So either put it into

<code>
finally {
out.close();
}
</code>

or see this simple example

<code>try {
    String content = s;
    File file = new File("/filename.txt");

    // if file doesnt exists, then create it
    if (!file.exists()) {
    file.createNewFile();
    }

    FileWriter fw = new FileWriter(file.getAbsoluteFile());
    BufferedWriter bw = new BufferedWriter(fw);
    bw.write(content);
    bw.close();
    System.out.println("Done");
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
</code>

Upvotes: 0

Roland
Roland

Reputation: 5438

It's better to use Apache Commons IO instead.

http://commons.apache.org/io/api-release/org/apache/commons/io/IOUtils.html should make the trick.

(Unless you are trying to learn the low-level stuff or actually knows why you can't use IOUtils for this case.)

Upvotes: 1

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136022

try this

public void content(String s) throws IOException { 
        try (BufferedReader br = new BufferedReader(new FileReader(s));
                PrintWriter pr = new PrintWriter(new File("e:\\OP.txt"))) {
            for (String line; (line = br.readLine()) != null;) {
                pr.println(line);
            }
        }
}

Upvotes: 0

PermGenError
PermGenError

Reputation: 46408

close your PrintWriter inside finally block out side the loop

 finally {

         out.close();
    }

Upvotes: 1

RoflcoptrException
RoflcoptrException

Reputation: 52229

You shouldn't create your PrintWriter inside the loop every time:

public void content(String s) {
   BufferedReader br=new BufferedReader(new FileReader(s));

   try {
      PrintWriter out=new PrintWriter(new FileWriter("e:\\OP.txt"));
      String read=null;

      while((read=br.readLine())!=null) {
         out.write(read);
      }
   } catch(Exception e) {
      //do something meaningfull}
   } finally {
      out.close();
   }
}

Aditionally, as others have mentioned add a finally block, do not silently catch the exception, and follow the Java Coding Conventions.

Upvotes: 7

Related Questions