KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > BackUp


1 import java.io.*;
2
3 /** Utility class that provides static methods for backing up and restoring files.
4 * The backed up file name if the original filename + .bak*/

5 public final class BackUp{
6     private static final int BUFFER_SIZE=1024;
7     private static final String JavaDoc BAK=".bak";
8     
9     /** Backs up a file.
10     * @param f The file to back up.
11     * @exception IOException If there's a problem creating the backup-*/

12     public static void backUp(File f) throws IOException{
13         File buf=new File(f.getParent(),f.getName()+BAK);
14         FileInputStream fis=new FileInputStream(f);
15         FileOutputStream fos=new FileOutputStream(buf,false);
16         byte[] buffer=new byte[BUFFER_SIZE];
17         int r=fis.read(buffer,0,BUFFER_SIZE);
18         while(r!=-1){
19             if(r>0){
20                 fos.write(buffer,0,r);
21             }
22             r=fis.read(buffer,0,BUFFER_SIZE);
23         }
24         fis.close();
25         fos.flush();
26         fos.close();
27     }
28     
29     /** Restores a file from a back.up
30     * @param f The <b>original</b> File that was backed up.
31     * @exception IOException If there's a problem creating the backup-*/

32     public static void restore(File f) throws IOException{
33         File buf=new File(f.getParent(),f.getName()+BAK);
34         if(!buf.isFile()){
35             throw new IOException(f.getName()+" does not have a backup.");
36         }
37         FileInputStream fis=new FileInputStream(buf);
38         FileOutputStream fos=new FileOutputStream(f,false);
39         byte[] buffer=new byte[BUFFER_SIZE];
40         int r=fis.read(buffer,0,BUFFER_SIZE);
41         while(r!=-1){
42             if(r>0){
43                 fos.write(buffer,0,r);
44             }
45             r=fis.read(buffer,0,BUFFER_SIZE);
46         }
47         fis.close();
48         fos.flush();
49         fos.close();
50     }
51 }
52
53
54
Popular Tags