Package anvil.core.io

Source Code of anvil.core.io.AnyFile

/*
* $Id: AnyFile.java,v 1.41 2002/09/16 08:05:02 jkl Exp $
*
* Copyright (c) 2002 Njet Communications Ltd. All Rights Reserved.
*
* Use is subject to license terms, as defined in
* Anvil Sofware License, Version 1.1. See LICENSE
* file, or http://njet.org/license-1.1.txt
*/
package anvil.core.io;

import anvil.core.Any;
import anvil.core.AnyAbstractClass;
import anvil.core.AnyBinary;
import anvil.core.AnyString;
import anvil.core.AnyList;
import anvil.core.Array;
import anvil.core.Serialization;
import anvil.core.UnserializationException;
import anvil.core.Unserializer;
import anvil.core.Serializer;
import anvil.script.Context;
import anvil.java.util.BindingEnumeration;
import anvil.java.io.GenericInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilePermission;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.io.Writer;
import java.net.MalformedURLException;
import java.util.Enumeration;

/// @class File
/// A representation of file and directory pathnames.
///
/// @operator enumeration
/// If this file points directory, return enumeration
/// of files in directory, otherwise returns enumeration
/// of lines in file.
/// @synopsis enumeration * InstanceOfFile

/**
* class AnyFile
*
* @author: Jani Lehtim�ki
*/
public class AnyFile extends AnyAbstractClass
{


  /// @constructor File
  /// Creates new File object.
  /// @synopsis File(string file)
  /// @synopsis File(string parent, string child)
  /// @synopsis File(File parent, string child)
  /// @param file Path to file
  /// @param parent Base path to merged with child
  /// @param child Child path to merged with parent
  public static final Object[] newInstance = { "context", "*child", null };
  public static final Any newInstance(Any p1, Any p2)
  {
    File file;
    if (p2 != null) {
      if (p1 instanceof AnyFile) {
        file = new File((File)p1.toObject(), IOModule.toPathname(p2));
      } else {
        file = new File(IOModule.toPathname(p1), IOModule.toPathname(p2));
      }
    } else {
      file = new File(IOModule.toPathname(p1));
    }
    return Any.create(file);
  }


 

  protected File _file;
  protected RandomAccessFile _access = null;
 

 
  public static final Any create(String file)
  {
    return new AnyFile(new File(file));
  }
 
 
  public AnyFile(File file)
  {
    _file = file;
  }
 

  public anvil.script.ClassType classOf()
  {
    return __class__;
  }
 

  public String toString()
  {
    return _file.toString();
  }



  public Writer toAnvil(Writer writer) throws IOException
  {
    writer.write("new anvil.io.File(\"");
    writer.write(anvil.util.Conversions.escape(_file.toString(), true));
    writer.write(')');
    writer.write('"');
    return writer;
  }


  public Writer toJava(Writer writer) throws IOException
  {
    writer.write("anvil.core.io.AnyFile.create(\"");
    writer.write(anvil.util.Conversions.escape(_file.toString(), true));
    writer.write('"');
    writer.write(')');
    return writer;
  }


  public anvil.codec.Code toCode(anvil.codec.Code code)
  {
    anvil.codec.ConstantPool pool = code.getPool();
    code.astring(_file.toString());
    code.invokestatic(code.getPool().addMethodRef("anvil/core/io/AnyFile",
      "create", "(Ljava/lang/String;)Lanvil/core/Any;"));
    return code;
 

  public Object toObject()
  {
    return _file;
  }


  public int hashCode()
  {
    return _file.hashCode();
  }


  public void serialize(Serializer serializer) throws IOException
  {
    if (serializer.register(this)) {
      return;
    }
    String s = _file.getAbsolutePath();
    serializer.write('F');
    serializer.write(s.length());
    serializer.write(':');
    serializer.writeUTF16(s);
  }


  public static final Any unserialize(Unserializer unserializer)
    throws UnserializationException
  {
    AnyFile file = new AnyFile(new File(unserializer.getUTF16String()));
    unserializer.register(file);
    return file;
  }

  public BindingEnumeration enumeration()
  {
    try {
      Context.getInstance().checkRead(_file.getPath());
      if (_file.isDirectory()) {
        File[] list = _file.listFiles();
        if (list == null) {
          return BindingEnumeration.EMPTY;
        }
        int n = list.length;
        Array files = new Array(n);
        for(int i=0; i<n; i++) {
          files.append(Any.create(list[i]));
        }    
        return files.keysAndElements();
       
      } else {
        return new InputStreamEnumeration(
          new GenericInputStream(new FileInputStream(_file)));
         
      }
     
    } catch (IOException e) {
      return BindingEnumeration.EMPTY;
    }
  }
 
 
  public boolean equals(Object o)
  {
    if (this == o) {
      return true;
    }
    if (o instanceof AnyFile) {
      return _file.equals(((AnyFile)o)._file);
    }
    return false;
  }
 
 
  /********* Exposed methods ************/

  /// @method getName
  /// Returns the name of file pointed by this File instance.
  /// @synopsis string getName()
  public Any m_getName()
  {
    return new AnyString(_file.getName());
  }

 
  /// @method getParent
  /// Returns the path of parent file pointed by this File instance.
  /// @synopsis string getParent()
  public Any m_getParent()
  {
    return new AnyString(_file.getParent());
  }
 
 
  /// @method getParentFile
  /// Returns the parent file pointed by this File instance.
  /// @synopsis File getParentFile()
  public Any m_getParentFile()
  {
    return Any.create(_file.getParentFile());
  }


  /// @method getPath
  /// Returns the path of file pointed by this File instance.
  /// @synopsis string getPath()
  public Any m_getPath()
  {
    return new AnyString(_file.getPath());
  }
 

  /// @method isAbsolute
  /// Tests if the file represented by this File object is an absolute pathname.
  /// @synopsis boolean isAbsolute()
  public Any m_isAbsolute()
  {
    return _file.isAbsolute() ? TRUE : FALSE;
  }
 

  /// @method getAbsolutePath
  /// Returns the absolute path.
  /// @synopsis string getAbsolutePath()
  public Any m_getAbsolutePath()
  {
    return new AnyString(_file.getAbsolutePath());
  }
 
 
  /// @method getAbsoluteFile
  /// Returns the absolute path as file.
  /// @synopsis File getAbsoluteFile()
  public Any m_getAbsoluteFile()
  {
    return Any.create(_file.getAbsoluteFile());
  }
 
 
  /// @method getCanonicalPath
  /// Returns the canonical path.
  /// @synopsis string getCanonicalPath()
  public Any m_getCanonicalPath(Context context)
  {
    try {
      return new AnyString(_file.getCanonicalPath());
    } catch (IOException e) {
      throw context.exception(e);
    }
  }
 
 
  /// @method getCanonicalFile
  /// Returns the canonical path as File.
  /// @synopsis File getCanonicalFile()
  public Any m_getCanonicalFile(Context context)
  {
    try {
      return Any.create(_file.getCanonicalFile());
    } catch (IOException e) {
      throw context.exception(e);
    }
  }
 

  /// @method toURL
  /// Converts path on this File variable to file:// URL.
  /// @synopsis URL toURL()
  public Any m_toURL(Context context)
  {
    try {
      return Any.create(_file.toURL());
    } catch (java.net.MalformedURLException e) {
      throw context.exception(e);
    }
  }
 

  /// @method canRead
  /// Checks if the contents of file can be read.
  /// @synopsis boolean canRead()
  public Any m_canRead(Context context)
  {
    context.checkRead(_file.getPath());
    return _file.canRead() ? TRUE : FALSE;
  }
 

  /// @method canWrite
  /// Checks if the contents of file can be written.
  /// @synopsis boolean canWrite()
  public Any m_canWrite(Context context)
  {
    context.checkWrite(_file.getPath());
    return _file.canWrite() ? TRUE : FALSE;
  }
 

  /// @method exists
  /// Checks if the file actually exists.
  /// @synopsis boolean exists()
  public Any m_exists(Context context)
  {
    context.checkRead(_file.getPath());
    return _file.exists() ? TRUE : FALSE;
  }
 

  /// @method isDirectory
  /// Checks if the file is directory.
  /// @synopsis boolean isDirectory()
  public Any m_isDirectory(Context context)
  {
    context.checkRead(_file.getPath());
    return _file.isDirectory() ? TRUE : FALSE;
  }
 

  /// @method isFile
  /// Checks if the file is regular file.
  /// @synopsis boolean isFile()
  public Any m_isFile(Context context)
  {
    context.checkRead(_file.getPath());
    return _file.isFile() ? TRUE : FALSE;
  }
 

  /// @method isHidden
  /// Checks is the file is hidden.
  /// @synopsis boolean isHidden()
  public Any m_isHidden(Context context)
  {
    context.checkRead(_file.getPath());
    return _file.isHidden() ? TRUE : FALSE;
  }
 

  /// @method lastModified
  /// Gets the timestamp of last modification (milliseconds
  /// since 1.1.1970).
  /// @synopsis int lastModified()
  public Any m_lastModified(Context context)
  {
    context.checkRead(_file.getPath());
    return Any.create(_file.lastModified());
  }
 


  /// @method createNewFile
  /// Creates the a new, empty file if and only if the file with this
  /// name does not yeat exist.
  /// @synopsis boolean createNewFile()
  /// @return <code>true</code> if the named file does not exist
  /// and was successfully created; <code>false</code> if the named
  /// file already exists
  /// @throws IOError If an I/O error occurred
  public Any m_createNewFile(Context context)
  {
    context.checkWrite(_file.getPath());
    try {
      return _file.createNewFile() ? TRUE : FALSE;
    } catch (IOException e) {
      throw context.exception(e);
    }
  }
 
 
  /// @method remove
  /// Removes the file. If this pathname denotes a directory, then the
  /// directory must be empty in order to be deleted.
  /// @return <code>true</code> if and only if the file or directory is
  /// successfully remove; false otherwise
  /// @synopsis boolean remove()
  public Any m_remove(Context context)
  {
    context.checkDelete(_file.getPath());
    return _file.delete() ? TRUE : FALSE;
  }
 
 
  /// @method removeOnExit
  /// Requests that the file or directory denoted by this abstract
  /// pathname be deleted when the virtual machine terminates.
  /// @synopsis File removeOnExit()
  public Any m_removeOnExit(Context context)
  {
    context.checkDelete(_file.getPath());
    _file.deleteOnExit();
    return this;
  }
 
 
  /// @method list
  /// Returns an array of strings naming the files and directories
  /// in the directory denoted by this pathname.
  /// @synopsis array list()
  /// @return array of strings
  public Any m_list(Context context)
  {
    context.checkRead(_file.getPath());
    String[] list = _file.list();
    if (list == null) {
      return NULL;
    }
    int n = list.length;
    Array files = new Array(n);
    for(int i=0; i<n; i++) {
      Any name = Any.create(list[i]);
      files.put(name, name);
    }
    return files;
  }
 
 
  /// @method listFiles
  /// Returns an array of File objects describing the files and directories
  /// in the directory denoted by this pathname.
  /// @synopsis array listFiles()
  /// @return array of Files containing files and directories, or
  /// <code>null</code> if this File does not point to directory.
  public Any m_listFiles(Context context)
  {
    context.checkRead(_file.getPath());
    File[] list = _file.listFiles();
    if (list == null) {
      return NULL;
    }
    int n = list.length;
    Array files = new Array(n);
    for(int i=0; i<n; i++) {
      File file = list[i];
      files.put(Any.create(file.getName()), new AnyFile(file));
    }
    return files;
  }
   
 
  /// @method mkdir
  /// Creates the last part of path.
  /// @synopsis boolean mkdir()
  /// @return <code>true</code> if and only if the directory was created;
  /// <code>false</code> otherwise
  public Any m_mkdir(Context context)
  {
    context.checkWrite(_file.getPath());
    return _file.mkdir() ? TRUE : FALSE;
  }
 
 
  /// @method mkdirs
  /// Creates the full path.
  /// @synopsis boolean mkdirs()
  /// @return <code>true</code> if and only if all directories was created;
  /// <code>false</code> otherwise
  public Any m_mkdirs(Context context)
  {
    context.checkWrite(_file.getPath());
    return _file.mkdirs() ? TRUE : FALSE;
  }
 
 
  /// @method renameTo
  /// Renames the file.
  /// @synopsis boolean renameTo(string newName)
  /// @synopsis boolean renameTo(File newName)
  /// @return <code>true</code> if and only if the renaming succeeded;
  /// <code>false</code> otherwise
  public static final Object[] p_renameTo = new Object[] { null, "newName" };
  public Any m_renameTo(Context context, Any dest)
  {
    context.checkWrite(_file.getPath());
    File file = null;
    if (dest instanceof AnyFile) {
      file = ((AnyFile)dest)._file;
    } else {
      file = new File(dest.toString());
    }
    context.checkWrite(file.getPath());
    return _file.renameTo(file) ? TRUE : FALSE;
  }
 
 
  /// @method setLastModified
  /// Sets last modification timestamp.
  /// @synopsis boolean setLastModified(int timestamp)
  public static final Object[] p_setLastModified = new Object[] { null, "timestamp" };
  public Any m_setLastModified(Context context, long timestamp)
  {
    context.checkWrite(_file.getPath());
    return _file.setLastModified(timestamp) ? TRUE : FALSE;
  }
 

  /// @method setReadOnly
  /// Sets the file readonly.
  /// @synopsis boolean setReadOnly()
  public Any m_setReadOnly(Context context)
  {
    context.checkWrite(_file.getPath());
    return _file.setReadOnly() ? TRUE : FALSE;
  }


  /// @method openInput
  /// Opens an input stream to file.
  /// @synopsis InputStream openInput()
  /// @throws IOError If an I/O error occurs
  public Any m_openInput(Context context)
  {
    context.checkRead(_file.getPath());
    try {
      return new AnyInputStream(new FileInputStream(_file));
    } catch (IOException e) {
      throw context.exception(e);
    }
  } 


  /// @method openOutput
  /// Opens an output stream to file.
  /// @synopsis OutputStream openOutput()
  /// @throws IOError If an I/O error occurs
  public Any m_openOutput(Context context)
  {
    context.checkWrite(_file.getPath());
    try {
      return new AnyOutputStream(new BufferedOutputStream(
        new FileOutputStream(_file)));
    } catch (IOException e) {
      throw context.exception(e);
    }
  } 


  private void ensureOpen(Context context) throws IOException
  {
    ensureOpen(context, "r");
  }


  private void ensureOpen(Context context, String mode) throws IOException
  {
    if (mode.indexOf('r')>=0) {
      context.checkRead(_file.getPath());
    }
    if (mode.indexOf('w')>=0) {
      context.checkWrite(_file.getPath());
    }
    if (_access == null) {
      _access = new RandomAccessFile(_file, mode);
    }
  }


  /// @method open
  /// Opens file for reading (mode is <code>"r"</code>) or
  /// writing (mode is <code>"w"</code>). If the mode is
  /// <code>"rw"</code> and it does not exists, attempt is made
  /// to create it.
  /// @synopsis File open()
  /// @synopsis File open(string mode)
  /// @throws IOError If an I/O error occurs
  public static final Object[] p_open = new Object[] { null, "*mode", null };
  public Any m_open(Context context, String mode)
  {
    if (mode == null) {
      mode = "r";
    }
    try {
      ensureOpen(context, mode);
      return this;
    } catch (IOException e) {
      throw context.exception(e);
    }
  }
 

  /// @method close
  /// Closes this random access file stream and releases any system resources associated
  /// with the stream. A closed file cannot perform input or output operations.
  /// @synopsis File close()
  /// @throws IOError If an I/O error occurs
  public Any m_close(Context context)
  {
    if (_access == null) {
      return this;
    }
    try {
      _access.close();
      _access = null;
      return this;
    } catch (IOException e) {
      throw context.exception(e);
    }
  }
 

  /// @method sync
  /// Attempts to synchronize the changes back to disk.
  /// @synopsis File sync()
  /// @throws IOError If an I/O error occurs
  public Any m_sync(Context context)
  {
    if (_access == null) {
      return this;
    }
    try {
      _access.getFD().sync();
      return this;
    } catch (IOException e) {
      throw context.exception(e);
    }
  }
 

  /// @method length
  /// Return the length of file.
  /// @synopsis int length()
  /// @throws IOError If an I/O error occurs
  public Any m_length(Context context)
  {
    try {
      if (_access == null) {
        context.checkRead(_file.getPath());
        return Any.create(_file.length());
      } else {
        return Any.create(_access.length());
      }
    } catch (IOException e) {
      throw context.exception(e);
    }
  }

 
  /// @method setLength
  /// Sets the length of file to 'newLength'. If 'newLength' is greater
  /// than the current length, contents of extended section is undefined.
  /// @synopsis int setLength(int newLength)
  /// @throws IOError If an I/O error occurs
  public static final Object[] p_setLength = new Object[] { null, "newLength" };
  public Any m_setLength(Context context, long newLength)
  {
    if (newLength < 0) {
      newLength = 0;
    }
    try {
      ensureOpen(context, "rw");
      _access.setLength(newLength);
      return TRUE;
    } catch (IOException e) {
      throw context.exception(e);
    }
  }
 
 
 
  /// @method seek
  /// Seeks file pointer to new position.
  /// @synopsis File seek(int pos)
  /// @param pos the offset position, measured in bytes
  /// from the beginning of the file,
  /// @throws IOError If an I/O error occurs
  public static final Object[] p_seek = new Object[] { null, "position" };
  public Any m_seek(Context context, long pos)
  {
    if (pos < 0) {
      pos = 0;
    }
    try {
      ensureOpen(context);
      _access.seek(pos);
      return this;
    } catch (IOException e) {
      throw context.exception(e);
    }
  } 


  /// @method getPos
  /// Returns the current file position.
  /// @synopsis int getPos()
  /// @throws IOError If an I/O error occurs
  public Any m_getPos(Context context)
  {
    try {
      ensureOpen(context);
      return Any.create(_access.getFilePointer());
    } catch (IOException e) {
      throw context.exception(e);
    }
  } 


  /// @method skip
  /// Skips given amount of bytes.
  /// @synopsis int skip(int amount)
  /// @param amount Amount of bytes to skip
  /// @return number of bytes skipped.
  /// @throws IOError If an I/O error occurs
  public static final Object[] p_skip = new Object[] { null, "count" };
  public Any m_skip(Context context, int amount)
  {
    if (amount < 0) {
      return ZERO;
    }
    try {
      ensureOpen(context);
      return Any.create(_access.skipBytes(amount));
    } catch (IOException e) {
      throw context.exception(e);
    }
  } 

 
  /// @method read
  /// @synopsis int read() ;
  /// Reads next byte from file
  /// @synopsis string read(int amount) ;
  /// Reads given amount of bytes from file.
  /// @param amout Amount of bytes to read
  /// @return string, or int, or <code>null</code> if end of stream
  /// encountered (and no bytes could not be read before it).
  /// @throws IOError If an I/O error occurs
  public static final Object[] p_read = new Object[] { null, "*bytes", null };
  public Any m_read(Context context, Any bytes)
  {
    try {
      if (bytes != null) {
        int amount = bytes.toInt();
        if (amount <= 0) {
          return EMPTY_STRING;
        }
        StringBuffer buffer = new StringBuffer(amount);
        int b;
        ensureOpen(context);
        while(((b = _access.read()) != -1) && (amount-- > 0)) {
          buffer.append((char)b);
        }
        return (b == -1) && (buffer.length() == 0) ?
          NULL : new AnyString(buffer.toString());
         
      } else {
        ensureOpen(context);
        int b = _access.read();
        return (b == -1) ? NULL : Any.create(b);
       
      }
    } catch (IOException e) {
      throw context.exception(e);
    }   
  }
 
 
  /// @method readLine
  /// Reads a single line from file.
  /// @synopsis string readLine()
  /// @return line in string, or <code>null</code> if an error occured
  /// or end of stream encountered (and no bytes could not be read
  /// before it).
  /// @throws IOError If an I/O error occurs
  public Any m_readLine(Context context)
  {
    try {
      ensureOpen(context);
      return Any.create(_access.readLine());
    } catch (IOException e) {
      throw context.exception(e);
    }   
  }


  /// @method readLines
  /// @synopsis list readLines() ;
  /// Reads as many lines as possible from this file
  /// @synopsis list readLines(int maxLines) ;
  /// Reads upto given amount of lines from this file
  /// @param maxLines Maximum number of lines to read
  /// @return List of strings
  /// @throws IOError If an I/O error occurs
  public static final Object[] p_readLines = new Object[] { null, "*maxLines", null };
  public Any m_readLines(Context context, Any max_)
  {
    int max = 0;
    if (max_ != null) {
      max = max_.toInt();
      if (max < 0) {
        max = 0;
      }
    }
    try {
      ensureOpen(context);
      String line;
      if (max == 0) {
        AnyList lines = new AnyList(new Any[8], 0);
        while((line = _access.readLine()) != null) {
          lines.append(Any.create(line));
        }
        return lines;
      } else {
        Any[] lines = new Any[max];
        int index = 0;
        while(max-- > 0) {
          line = _access.readLine();
          if (line == null) {
            break;
          }
          lines[index++] = Any.create(line);
        }
        return new AnyList(lines, index);
      }
    } catch (IOException e) {
      throw context.exception(e);
    }   
  }
   
 

  /// @method readData
  /// Reads and returns next serialized data from file.
  /// @synopsis object readData()
  /// @throws CorruptedSerialization If serialized data is correupted
  /// @throws IOError If an I/O error occurs
  public Any m_readData(Context context)
  {
    try {
      ensureOpen(context);
      return Serialization.unserialize(context, _access);
    } catch (UnserializationException e) {
      throw context.CorruptedSerialization();
    } catch (IOException e) {
      throw context.exception(e);
    }
  } 


  /// @method readBinary
  /// Reads from file to given binary.
  /// @synopsis int readBinary(binary bin)
  /// @synopsis int readBinary(binary bin, int offset)
  /// @synopsis int readBinary(binary bin, int offset, int length)
  /// @param bin The binary into which the data is read
  /// @param offset The start offset of the data
  /// @param length The maximum number of bytes to read
  /// @return the amount of bytes read, or -1 if there is no more
  /// data because the end of file has been reached.
  /// @throws IOError If an I/O error occurs
  public static final Object[] p_readBinary = new Object[] { null, "array", "*offset", null, "*length", null };
  public Any m_readBinary(Context context, Any binary, Any offset_, Any length_)
  {
    byte[] array = null;
    if (binary.isBinary()) {
      array = binary.toBinary();
    } else {
      throw context.BadParameter("First parameter it not binary");
    }
    try {
      ensureOpen(context);
      int size = array.length;
      int offset = 0;
      int length = size;
      if (offset_ != null) {
        offset = offset_.toInt();
        if (length_ != null) {
          length = length_.toInt();
        }
        if (offset < 0) {
          offset = 0;
        }
        if (offset >= size) {
          return ZERO;
        }
        if (offset + length > size) {
          length = size - offset;
        }     
      }
      return Any.create(_access.read(array, offset, length));
     
    } catch (IOException e) {
      throw context.exception(e);
    }
  }

 


  /// @method write
  /// @synopsis File write(int byte) ; Writes single byte to file
  /// @synopsis File write(binary bin) ; Writes bytes to file
  /// @synopsis File write(string text) ; Writes text to file
  /// @throws IOError If an I/O error occurs
  public static final Object[] p_write = new Object[] { null, "values" };
  public Any m_write(Context context, Any[] parameters)
  {
    int n = parameters.length;
    try {
      ensureOpen(context, "rw");
      for(int i=0; i<n; i++) {
        Any value = parameters[i];
        switch(value.typeOf()) {
        case IS_NULL:
        case IS_UNDEFINED:
          break;
        case IS_INT:
          _access.write(value.toInt());
          break;
        case IS_BINARY:
          n = value.sizeOf();
          if (n > 0) {
            _access.write(value.toBinary(), 0, n);
          }
          break;
        default:
          String buffer = value.toString();
          if (buffer.length()>0) {
            _access.writeBytes(buffer);
          }
        }
      }
      return this;
    } catch (IOException e) {
      throw context.exception(e);
    }
  }


  /// @method writeBinary
  /// Writes the contents of binary to file.
  /// @synopsis File writeBinary(binary bin)
  /// @synopsis File writeBinary(binary bin, int offset, int length)
  /// @param bin The binary from which the data is written
  /// @param offset The start offset of the data
  /// @param length The number of bytes to write
  /// @throws IOError If an I/O error occurs
  public static final Object[] p_writeBinary = new Object[] { null, "array", "*offset", null, "*length", null };
  public Any m_writeBinary(Context context, Any binary, Any offset_, Any length_)
  {
    byte[] array;
    if (binary.isBinary()) {
      array = binary.toBinary();
    } else {
      throw context.BadParameter("First parameter it not binary");
    }
    int size = array.length;
    int offset = 0;
    int length = size;
    if (offset_ != null) {
      offset = offset_.toInt();
      if (length_ != null) {
        length = length_.toInt();
      }
      if (offset < 0) {
        offset = 0;
      }
      if (offset >= size) {
        return TRUE;
      }
      if (offset + length > size) {
        length = size - offset;
      }
    }
    try {
      ensureOpen(context, "rw");
      _access.write(array, offset, length);
      return TRUE;
    } catch (IOException e) {
      throw context.exception(e);
    }
  }
 

  /// @method writeData
  /// Serializes parameters to file.
  /// @synopsis File writeData(object data, ...)
  /// @param data Data to serialize
  /// @throws IOError If an I/O error occurs
  public static final Object[] p_writeData = new Object[] { null, "values" };
  public Any m_writeData(Context context, Any[] parameters)
  {
    int n = parameters.length;
    try {
      ensureOpen(context, "rw");
      for(int i=0; i<n; i++) {
        Serialization.serialize(context, parameters[i], _access);
      }
      return this;
    } catch (IOException e) {
      throw context.exception(e);
    }
  }


  public static final anvil.script.compiler.NativeClass __class__ =
    new anvil.script.compiler.NativeClass("File", AnyFile.class,
    //DOC{{
    ""+
      " @class File\n" +
      " A representation of file and directory pathnames. \n" +
      "\n" +
      " @operator enumeration\n" +
      " If this file points directory, return enumeration\n" +
      " of files in directory, otherwise returns enumeration\n" +
      " of lines in file.\n" +
      " @synopsis enumeration * InstanceOfFile\n" +
      " @constructor File\n" +
      " Creates new File object.\n" +
      " @synopsis File(string file)\n" +
      " @synopsis File(string parent, string child)\n" +
      " @synopsis File(File parent, string child)\n" +
      " @param file Path to file\n" +
      " @param parent Base path to merged with child\n" +
      " @param child Child path to merged with parent\n" +
      " @method getName\n" +
      " Returns the name of file pointed by this File instance.\n" +
      " @synopsis string getName()\n" +
      " @method getParent\n" +
      " Returns the path of parent file pointed by this File instance.\n" +
      " @synopsis string getParent()\n" +
      " @method getParentFile\n" +
      " Returns the parent file pointed by this File instance.\n" +
      " @synopsis File getParentFile()\n" +
      " @method getPath\n" +
      " Returns the path of file pointed by this File instance.\n" +
      " @synopsis string getPath()\n" +
      " @method isAbsolute \n" +
      " Tests if the file represented by this File object is an absolute pathname.\n" +
      " @synopsis boolean isAbsolute()\n" +
      " @method getAbsolutePath\n" +
      " Returns the absolute path.\n" +
      " @synopsis string getAbsolutePath()\n" +
      " @method getAbsoluteFile\n" +
      " Returns the absolute path as file.\n" +
      " @synopsis File getAbsoluteFile()\n" +
      " @method getCanonicalPath\n" +
      " Returns the canonical path.\n" +
      " @synopsis string getCanonicalPath()\n" +
      " @method getCanonicalFile\n" +
      " Returns the canonical path as File.\n" +
      " @synopsis File getCanonicalFile()\n" +
      " @method toURL\n" +
      " Converts path on this File variable to file:// URL.\n" +
      " @synopsis URL toURL()\n" +
      " @method canRead\n" +
      " Checks if the contents of file can be read.\n" +
      " @synopsis boolean canRead()\n" +
      " @method canWrite \n" +
      " Checks if the contents of file can be written.\n" +
      " @synopsis boolean canWrite()\n" +
      " @method exists\n" +
      " Checks if the file actually exists.\n" +
      " @synopsis boolean exists()\n" +
      " @method isDirectory\n" +
      " Checks if the file is directory.\n" +
      " @synopsis boolean isDirectory()\n" +
      " @method isFile \n" +
      " Checks if the file is regular file.\n" +
      " @synopsis boolean isFile()\n" +
      " @method isHidden\n" +
      " Checks is the file is hidden.\n" +
      " @synopsis boolean isHidden()\n" +
      " @method lastModified\n" +
      " Gets the timestamp of last modification (milliseconds\n" +
      " since 1.1.1970).\n" +
      " @synopsis int lastModified()\n" +
      " @method createNewFile\n" +
      " Creates the a new, empty file if and only if the file with this\n" +
      " name does not yeat exist.\n" +
      " @synopsis boolean createNewFile()\n" +
      " @return <code>true</code> if the named file does not exist \n" +
      " and was successfully created; <code>false</code> if the named \n" +
      " file already exists\n" +
      " @throws IOError If an I/O error occurred\n" +
      " @method remove \n" +
      " Removes the file. If this pathname denotes a directory, then the\n" +
      " directory must be empty in order to be deleted.\n" +
      " @return <code>true</code> if and only if the file or directory is \n" +
      " successfully remove; false otherwise\n" +
      " @synopsis boolean remove()\n" +
      " @method removeOnExit \n" +
      " Requests that the file or directory denoted by this abstract \n" +
      " pathname be deleted when the virtual machine terminates.\n" +
      " @synopsis File removeOnExit()\n" +
      " @method list \n" +
      " Returns an array of strings naming the files and directories \n" +
      " in the directory denoted by this pathname. \n" +
      " @synopsis array list()\n" +
      " @return array of strings\n" +
      " @method listFiles\n" +
      " Returns an array of File objects describing the files and directories \n" +
      " in the directory denoted by this pathname. \n" +
      " @synopsis array listFiles()\n" +
      " @return array of Files containing files and directories, or \n" +
      " <code>null</code> if this File does not point to directory.\n" +
      " @method mkdir \n" +
      " Creates the last part of path.\n" +
      " @synopsis boolean mkdir()\n" +
      " @return <code>true</code> if and only if the directory was created; \n" +
      " <code>false</code> otherwise\n" +
      " @method mkdirs \n" +
      " Creates the full path.\n" +
      " @synopsis boolean mkdirs()\n" +
      " @return <code>true</code> if and only if all directories was created; \n" +
      " <code>false</code> otherwise\n" +
      " @method renameTo\n" +
      " Renames the file.\n" +
      " @synopsis boolean renameTo(string newName)\n" +
      " @synopsis boolean renameTo(File newName)\n" +
      " @return <code>true</code> if and only if the renaming succeeded; \n" +
      " <code>false</code> otherwise\n" +
      " @method setLastModified\n" +
      " Sets last modification timestamp.\n" +
      " @synopsis boolean setLastModified(int timestamp)\n" +
      " @method setReadOnly\n" +
      " Sets the file readonly.\n" +
      " @synopsis boolean setReadOnly()\n" +
      " @method openInput\n" +
      " Opens an input stream to file.\n" +
      " @synopsis InputStream openInput()\n" +
      " @throws IOError If an I/O error occurs\n" +
      " @method openOutput\n" +
      " Opens an output stream to file.\n" +
      " @synopsis OutputStream openOutput()\n" +
      " @throws IOError If an I/O error occurs\n" +
      " @method open\n" +
      " Opens file for reading (mode is <code>\"r\"</code>) or \n" +
      " writing (mode is <code>\"w\"</code>). If the mode is \n" +
      " <code>\"rw\"</code> and it does not exists, attempt is made\n" +
      " to create it.\n" +
      " @synopsis File open()\n" +
      " @synopsis File open(string mode)\n" +
      " @throws IOError If an I/O error occurs\n" +
      " @method close\n" +
      " Closes this random access file stream and releases any system resources associated\n" +
      " with the stream. A closed file cannot perform input or output operations.\n" +
      " @synopsis File close()\n" +
      " @throws IOError If an I/O error occurs\n" +
      " @method sync\n" +
      " Attempts to synchronize the changes back to disk.\n" +
      " @synopsis File sync()\n" +
      " @throws IOError If an I/O error occurs\n" +
      " @method length\n" +
      " Return the length of file.\n" +
      " @synopsis int length()\n" +
      " @throws IOError If an I/O error occurs\n" +
      " @method setLength\n" +
      " Sets the length of file to 'newLength'. If 'newLength' is greater\n" +
      " than the current length, contents of extended section is undefined.\n" +
      " @synopsis int setLength(int newLength)\n" +
      " @throws IOError If an I/O error occurs\n" +
      " @method seek\n" +
      " Seeks file pointer to new position.\n" +
      " @synopsis File seek(int pos)\n" +
      " @param pos the offset position, measured in bytes \n" +
      " from the beginning of the file,\n" +
      " @throws IOError If an I/O error occurs\n" +
      " @method getPos \n" +
      " Returns the current file position.\n" +
      " @synopsis int getPos()\n" +
      " @throws IOError If an I/O error occurs\n" +
      " @method skip\n" +
      " Skips given amount of bytes. \n" +
      " @synopsis int skip(int amount)\n" +
      " @param amount Amount of bytes to skip\n" +
      " @return number of bytes skipped.\n" +
      " @throws IOError If an I/O error occurs\n" +
      " @method read\n" +
      " @synopsis int read() ; \n" +
      " Reads next byte from file\n" +
      " @synopsis string read(int amount) ; \n" +
      " Reads given amount of bytes from file. \n" +
      " @param amout Amount of bytes to read\n" +
      " @return string, or int, or <code>null</code> if end of stream \n" +
      " encountered (and no bytes could not be read before it).\n" +
      " @throws IOError If an I/O error occurs\n" +
      " @method readLine \n" +
      " Reads a single line from file. \n" +
      " @synopsis string readLine()\n" +
      " @return line in string, or <code>null</code> if an error occured\n" +
      " or end of stream encountered (and no bytes could not be read\n" +
      " before it).\n" +
      " @throws IOError If an I/O error occurs\n" +
      " @method readLines \n" +
      " @synopsis list readLines() ; \n" +
      " Reads as many lines as possible from this file\n" +
      " @synopsis list readLines(int maxLines) ;\n" +
      " Reads upto given amount of lines from this file\n" +
      " @param maxLines Maximum number of lines to read\n" +
      " @return List of strings\n" +
      " @throws IOError If an I/O error occurs\n" +
      " @method readData \n" +
      " Reads and returns next serialized data from file.\n" +
      " @synopsis object readData()\n" +
      " @throws CorruptedSerialization If serialized data is correupted\n" +
      " @throws IOError If an I/O error occurs\n" +
      " @method readBinary \n" +
      " Reads from file to given binary. \n" +
      " @synopsis int readBinary(binary bin)\n" +
      " @synopsis int readBinary(binary bin, int offset)\n" +
      " @synopsis int readBinary(binary bin, int offset, int length)\n" +
      " @param bin The binary into which the data is read\n" +
      " @param offset The start offset of the data\n" +
      " @param length The maximum number of bytes to read\n" +
      " @return the amount of bytes read, or -1 if there is no more\n" +
      " data because the end of file has been reached.\n" +
      " @throws IOError If an I/O error occurs\n" +
      " @method write\n" +
      " @synopsis File write(int byte) ; Writes single byte to file\n" +
      " @synopsis File write(binary bin) ; Writes bytes to file\n" +
      " @synopsis File write(string text) ; Writes text to file\n" +
      " @throws IOError If an I/O error occurs\n" +
      " @method writeBinary \n" +
      " Writes the contents of binary to file.\n" +
      " @synopsis File writeBinary(binary bin)\n" +
      " @synopsis File writeBinary(binary bin, int offset, int length)\n" +
      " @param bin The binary from which the data is written\n" +
      " @param offset The start offset of the data\n" +
      " @param length The number of bytes to write\n" +
      " @throws IOError If an I/O error occurs\n" +
      " @method writeData\n" +
      " Serializes parameters to file.\n" +
      " @synopsis File writeData(object data, ...)\n" +
      " @param data Data to serialize\n" +
      " @throws IOError If an I/O error occurs\n"
    //}}DOC
    );
  static {
    IOModule.class.getName();
  }
 
}
TOP

Related Classes of anvil.core.io.AnyFile

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.