File.length() problem

FileOutputStream out = new FileOutputStream("c:/test");
out.write("some data".getBytes());
out.flush(); out.close();
File f = new File("c:/test");
System.out.println("File size is: " + f.length());

Sometimes the outputs is:
File size is: 0


pls, help

dmgeAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
Venci75Connect With a Mentor Commented:
Hi dmge,

I had the same problem. This is because of flush() method desn't call the OS's flush(). To prevent from getting incorrect file size, use this:

FileOutputStream out = new FileOutputStream("c:/test");
out.write("some data".getBytes());
out.flush();
// OS level flush !!!
out.getFD().sync();
out.close();

File f = new File("c:/test");
System.out.println("File size is: " + f.length());



0
 
OviCommented:
And the writing take place or not ?
0
 
OviCommented:
I have no problem using this code :

import java.io.*;
import java.util.*;
import java.text.*;

public class FileWrite {
  public static void main(String[] args) {
    for(int i = 0; i<1000; i++) {
      File f = new File(System.getProperty("user.dir") + File.separator + "test.txt");
      try {
        BufferedWriter bw = new BufferedWriter(new FileWriter(f));
        bw.write("Test writing to file");
        bw.flush();
        bw.close();
      } catch(Exception e) { e.printStackTrace(); }
      System.out.println(i + " File : " + f.getAbsolutePath() + "; size : " + f.length());
    }
  }
}


0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
Venci75Commented:
Here you can find more information about this:
http://developer.java.sun.com/developer/bugParade/bugs/4290946.html
0
 
OviCommented:
This bug was reported against JDK 1.2.x, now there is JDK 1.4.
0
 
dmgeAuthor Commented:
This works!
You are right Ovi, but I have a requirement to be java 1.2 compatible.

Thanks for your help
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.