Avatar billede fredand Forsker
01. februar 2007 - 17:55 Der er 3 kommentarer og
1 løsning

How to Move a file in Java?

•   


Hello!

We are developing a app in Java for a customer.
The app creates a zip file that might be pretty big once a day.
This file is later fetched and removed by an other app.

In the spec the customer has this demand:

The zip file is first delivered to temporary folder Temp on the server.
To prohibit premature reading the zip file is then moved (by Move or Rename, not Copy) to output folder Output, lying beside Temp folder on the server.

My first question is:
I guess I then should to this with:
oldFile.renameTo(new File("newFile"))
Please correct me if I'm wrong.


My second question is how would I do if I should copy the file?
My guess is something like:
            FileOutputStream output = new FileOutputStream(newFile);
            FileInputStream input = new FileInputStream(oldFile);
            byte[] buffer = new byte[2048];
            int i = 0;
            while ((i = input.read(buffer)) != -1)
            {
                output.write(buffer,0,i);
            }
            input.close();
            output.close();

...or is there a smarter way?

My third question is
Is the expression "Move" something from C?
I guess then that in Java
oldFile.renameTo(new File("newFile"))
must be equal to that?

Best regards
Fredrik
Avatar billede arne_v Ekspert
01. februar 2007 - 18:13 #1
re 1)

looks rigth

re 2)

use a bigger buffer for sligtly better performance, but else it is OK

re 3)

move and rename are almost synonyms

traditionally:

rename = operation that will always be done just updating dirs/fileheaders

move = operation that will update dirs/fileheaders if possible but will
      actually read and write file content if necesarry

if you study the Java doc for renameTo, then it can do both
Avatar billede fredand Forsker
02. februar 2007 - 08:46 #2
Hello Arne!

Thanks for your great explanation.
You really must give a svar so I can reward you mate!
Best regards
Fredrik
Avatar billede arne_v Ekspert
02. februar 2007 - 15:27 #3
.
Avatar billede fredand Forsker
05. februar 2007 - 08:42 #4
Thanks alot!
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