Avatar billede hallstrom Nybegynder
29. oktober 2003 - 19:52 Der er 5 kommentarer og
1 løsning

How to know when the writing process of a text file is completed

By using a thread my program is constantly watching a specific directory on Windows 2000 for new text files. These text files are loaded into a database. The problem is that sometimes I happen to start the loading before the textfile has completed the download process (that is I get "the half" file which is very bad). I have tried to use the method canWrite in the class File but this method gives me TRUE even when the writing process of the text file is not finished! Any ideas to solve this?
Avatar billede arne_v Ekspert
29. oktober 2003 - 19:56 #1
before J2SE 1.4 : problem
J2SE 1.4 or newer : look at java.nio.channel.FileLock

(it can also be used java program <-> non-java program)
Avatar billede arne_v Ekspert
29. oktober 2003 - 19:57 #2
WHen you can get an exclusive lock on the file, then it is ready for
read.
Avatar billede arne_v Ekspert
29. oktober 2003 - 20:05 #3
There are an example at:
  http://www.absolutejava.com/main-articles/just-one-please/
(even though that example solves a different problem it should be easy
to apply to your problem)
Avatar billede arne_v Ekspert
29. oktober 2003 - 20:06 #4
Avatar billede arne_v Ekspert
29. oktober 2003 - 21:17 #5
Færdig metode:

    public static boolean fileready(String fnm) {
        try {
            FileLock lck = (new FileOutputStream(fnm, true)).getChannel().tryLock();
            return (lck != null);
        } catch (IOException ex) {
            return false;
        }
    }

[det er ret vigtigt at huske den append=true i constructoren !]
Avatar billede hallstrom Nybegynder
29. oktober 2003 - 21:48 #6
Thanks, now it seems to work!
Avatar billede Ny bruger Nybegynder

Din løsning...

Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.

Loading billede Opret Preview
Kategori
Kurser inden for grundlæggende programmering

Log ind eller opret profil

Hov!

For at kunne deltage på Computerworld Eksperten skal du være logget ind.

Det er heldigvis nemt at oprette en bruger: Det tager to minutter og du kan vælge at bruge enten e-mail, Facebook eller Google som login.

Du kan også logge ind via nedenstående tjenester