WebNFS Developer's Guide

Appendix B Simple XFile Sample Programs

Overview

Note that it is not important whether the source and destination files for these programs are local or remote.

Copying a File

This program does a simple file copy.

Usage:

% java xcopy src dest

Example B-1

import java.io.*;
import com.sun.xfile.*;
class xcopy {
     public static void main(String av[]) {
          try {
               String srcFile = av[0];	    
               String dstFile = av[1];	

               XFileInputStream  in  = new XFileInputStream(srcFile)	
               XFileOutputStream out = new XFileOutputStream(dstFile);

               int c;        
               byte[] buf = new byte[32768];            
               long elapsedtime = System.currentTimeMillis();
               int filesz = 0;		

               while ((c = in.read(buf)) > 0) {                
                    filesz += c;                
                    out.write(buf, 0, c);               
                    System.out.print("" + filesz);            
               }            

               System.out.println();       
               in.close();            
               out.close();            

               elapsedtime = System.currentTimeMillis() - elapsedtime;
               int rate = (int) (filesz / (elapsedtime / 1000.0) / 1024);
               System.err.println(filesz + " bytes copied @ " + rate + "Kb/sec");
          } catch (IOException e) {	    
                    System.err.println(e);        
          }    
     }
}

Recursive Copy

This program takes a file or a directory hierarchy and copies it somewhere else.

Usage:

% java rcopy src dest

Example B-2

import java.io.*;
import com.sun.xfile.*;
class rcopy {    
     static void copy(XFile src, XFile dst) throws IOException {
          if (src.isDirectory()) {            
               dst.mkdir();            
               String[] dirList = src.list();           
               for (int i = 0; i < dirList.length; i++)
                    String entry = dirList[i];      
                    copy(new XFile(src, entry), new XFile(dst, entry));
               }        
          } else {	                 // assume it's a file            
               XFileInputStream in  = new XFileInputStream(src);
               XFileOutputStream out = new XFileOutputStream(dst);

               int c;
               byte[] buf = new byte[32768];

               while ((c = in.read(buf)) > 0)                
                    out.write(buf, 0, c);                    

               in.close();            
               out.close();  
          }    
     }

     public static void main(String av[]) {
          try {            
               copy(new XFile(av[0]), new XFile(av[1])); 
          } catch (IOException e) {	    
               System.err.println(e);     
                    e.printStackTrace();       
          }    
     }
}