Пример #1
0
  public synchronized void freopen(Ruby runtime, String path, ModeFlags modes)
      throws DirectoryAsFileException, IOException, InvalidValueException, PipeException,
          BadDescriptorException {
    // flush first
    flushWrite();

    // reset buffer
    buffer.clear();
    if (reading) {
      buffer.flip();
    }

    this.modes = modes;

    if (descriptor.isOpen()) {
      descriptor.close();
    }

    if (path.equals("/dev/null") || path.equalsIgnoreCase("nul:") || path.equalsIgnoreCase("nul")) {
      descriptor = descriptor.reopen(new NullChannel(), modes);
    } else {
      String cwd = runtime.getCurrentDirectory();
      JRubyFile theFile = JRubyFile.create(cwd, path);

      if (theFile.isDirectory() && modes.isWritable()) throw new DirectoryAsFileException();

      if (modes.isCreate()) {
        if (theFile.exists() && modes.isExclusive()) {
          throw runtime.newErrnoEEXISTError("File exists - " + path);
        }
        theFile.createNewFile();
      } else {
        if (!theFile.exists()) {
          throw runtime.newErrnoENOENTError("file not found - " + path);
        }
      }

      // We always open this rw since we can only open it r or rw.
      RandomAccessFile file = new RandomAccessFile(theFile, modes.toJavaModeString());

      if (modes.isTruncate()) file.setLength(0L);

      descriptor = descriptor.reopen(file, modes);

      try {
        if (modes.isAppendable()) lseek(0, SEEK_END);
      } catch (PipeException pe) {
        // ignore, it's a pipe or fifo
      }
    }
  }
Пример #2
0
  /** Ensure close (especially flush) when we're finished with. */
  @Override
  public void finalize() throws Throwable {
    super.finalize();

    if (closedExplicitly) return;

    if (DEBUG) {
      LOG.info("finalize() for not explicitly closed stream");
    }

    // FIXME: I got a bunch of NPEs when I didn't check for nulls here...HOW?!
    if (descriptor != null && descriptor.isOpen()) {
      // tidy up
      finish(autoclose);
    }
  }