package com.db4o.lib;

import java.io.*;

public class File extends java.io.File
{
	public File(String path){
		super(path);
	}
	
	public File copy(String toPath){
		try{
			new File(toPath).mkdirs();
			
			RandomAccessFile raf = new RandomAccessFile(getAbsolutePath(),"r");
			int len = (int)raf.length();
			byte[] bytes = new byte[len];
			raf.read(bytes,0,len);
			raf.close();
			
			new java.io.File(toPath).delete();
			
			raf = new RandomAccessFile(toPath,"rw");
			raf.write(bytes);
			raf.close();
			
			return new com.db4o.lib.File(toPath);
		}
		catch(Exception e){}
		return null;
	}
	
	public void replace(String a_replace, String a_with){
		String path = getAbsolutePath();
		Str str = null;
		RandomAccessFile raf = null;
		int len = 0;
		byte l_bytes[] = null;
		try{
			if(! exists()){
				throw new Exception();
			}
			raf = new RandomAccessFile(path,"rw");
		}
		catch(Exception e){
			System.out.println("Failed to open file: " + path);
			return;
		}
			
		try{
			len = (int)raf.length();
			l_bytes = new byte[len];
			raf.read(l_bytes,0,len);
			raf.close();
		}
		catch(Exception e){
			System.out.println("File read denied:" + path);
			return;
		}
			
		str = new Str(new String(l_bytes));
		str.replace(a_replace,a_with);
		l_bytes = str.getString().getBytes();
		
		try{
			new File(path).delete();
		}catch(Exception e){
			System.out.println("File access denied: " + path);
			return;
		}
			
		try{
			raf = new RandomAccessFile(path,"rw");
			raf.write(l_bytes);
			raf.close();
		}
		catch(Exception e){
			System.out.println("File access denied: " + path);
			return;
		}
	}
}
