Exemplo n.º 1
1
  /**
   * Maps blah file with a random offset and checks to see if read from the ByteBuffer gets the
   * right line number
   */
  private static void testRead() throws Exception {
    StringBuilder sb = new StringBuilder();
    sb.setLength(4);

    for (int x = 0; x < 1000; x++) {
      try (FileInputStream fis = new FileInputStream(blah)) {
        FileChannel fc = fis.getChannel();

        long offset = generator.nextInt(10000);
        long expectedResult = offset / CHARS_PER_LINE;
        offset = expectedResult * CHARS_PER_LINE;

        MappedByteBuffer b = fc.map(MapMode.READ_ONLY, offset, 100);

        for (int i = 0; i < 4; i++) {
          byte aByte = b.get(i);
          sb.setCharAt(i, (char) aByte);
        }

        int result = Integer.parseInt(sb.toString());
        if (result != expectedResult) {
          err.println("I expected " + expectedResult);
          err.println("I got " + result);
          throw new Exception("Read test failed");
        }
      }
    }
  }
  public static void initialize() throws IOException, ConfigurationException {
    try (FileInputStream fis = new FileInputStream("CHANGES.txt")) {
      dataSource = ByteBuffer.allocateDirect((int) fis.getChannel().size());
      while (dataSource.hasRemaining()) {
        fis.getChannel().read(dataSource);
      }
      dataSource.flip();
    }

    SchemaLoader.loadSchema();
    SchemaLoader.schemaDefinition("");
  }
Exemplo n.º 3
0
  /**
   * Lis et retourne une piece depuis le fichier temporaire sur le disque (la piece doit exister)
   *
   * @param num : numéros de la piece
   */
  private synchronized byte[] readPieceTmpFile(int num) {
    if (num < 0 || num >= this.nbPieces()) {
      throw new IllegalArgumentException();
    }

    try {
      FileInputStream reader_tmp = new FileInputStream(this);
      FileChannel reader = reader_tmp.getChannel();

      int index_piece = Tools.readInt(reader, 4 + _key.length() + 4 + 4 + 4 * num);
      if (index_piece < 0) {
        throw new IllegalArgumentException();
      }

      int size = _piecesize;
      if (num == this.nbPieces() - 1) {
        size = _size - _piecesize * (this.nbPieces() - 1);
      }

      byte[] piece = Tools.readBytes(reader, this.headerSize() + _piecesize * index_piece, size);
      reader_tmp.close();

      return piece;
    } catch (Exception e) {
      System.out.println("Unable to read tmp file piece");
      e.printStackTrace();
    }
    return new byte[0];
  }
Exemplo n.º 4
0
  public static void main(String args[]) {
    try {
      aServer asr = new aServer();

      // file channel.
      FileInputStream is = new FileInputStream("");
      is.read();
      FileChannel cha = is.getChannel();
      ByteBuffer bf = ByteBuffer.allocate(1024);
      bf.flip();

      cha.read(bf);

      // Path Paths
      Path pth = Paths.get("", "");

      // Files some static operation.
      Files.newByteChannel(pth);
      Files.copy(pth, pth);
      // file attribute, other different class for dos and posix system.
      BasicFileAttributes bas = Files.readAttributes(pth, BasicFileAttributes.class);
      bas.size();

    } catch (Exception e) {
      System.err.println(e);
    }

    System.out.println("hello ");
  }
Exemplo n.º 5
0
  /**
   * @param startByte
   * @param endByte
   * @return
   * @throws Exception
   * @return true if all the bytes between in the file between startByte and endByte are null, false
   *     otherwise
   */
  private boolean isFilePortionNull(int startByte, int endByte) throws IOException {
    logger.config("Checking file portion:" + Hex.asHex(startByte) + ":" + Hex.asHex(endByte));
    FileInputStream fis = null;
    FileChannel fc = null;
    try {
      fis = new FileInputStream(file);
      fc = fis.getChannel();
      fc.position(startByte);
      ByteBuffer bb = ByteBuffer.allocateDirect(endByte - startByte);
      fc.read(bb);
      while (bb.hasRemaining()) {
        if (bb.get() != 0) {
          return false;
        }
      }
    } finally {
      if (fc != null) {
        fc.close();
      }

      if (fis != null) {
        fis.close();
      }
    }
    return true;
  }
Exemplo n.º 6
0
 public static void main(String[] arguments) {
   try {
     // read byte data into a byte buffer
     String data = "friends.dat";
     FileInputStream inData = new FileInputStream(data);
     FileChannel inChannel = inData.getChannel();
     long inSize = inChannel.size();
     ByteBuffer source = ByteBuffer.allocate((int) inSize);
     inChannel.read(source, 0);
     source.position(0);
     System.out.println("Original byte data:");
     for (int i = 0; source.remaining() > 0; i++) {
       System.out.print(source.get() + " ");
     }
     // convert byte data into character data
     source.position(0);
     Charset ascii = Charset.forName("US-ASCII");
     CharsetDecoder toAscii = ascii.newDecoder();
     CharBuffer destination = toAscii.decode(source);
     destination.position(0);
     System.out.println("\n\nNew character data:");
     for (int i = 0; destination.remaining() > 0; i++) {
       System.out.print(destination.get());
     }
     System.out.println();
   } catch (FileNotFoundException fne) {
     System.out.println(fne.getMessage());
   } catch (IOException ioe) {
     System.out.println(ioe.getMessage());
   }
 }
Exemplo n.º 7
0
  public String getFileBinaryBase64(String fileName) throws APIException {
    if ((new File(fileName)).exists()) {
      FileInputStream stream = null;
      try {
        stream = new FileInputStream(new File(fileName));
        FileChannel fc = stream.getChannel();
        MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
        /* Instead of using default, pass in a decoder. */
        byte[] b = new byte[bb.remaining()];
        bb.get(b);

        return Base64.encodeBytes(b);
      } catch (Exception e) {
        throw new APIException(fileName + " could not have its files extracte!");
      } finally {
        try {
          stream.close();
        } catch (Exception e) {
          throw new APIException(fileName + " could not be closed!");
        }
      }
    } else {
      throw new APIException(fileName + " doesn't exist!");
    }
  }
Exemplo n.º 8
0
 // Read up to 'len' bytes of Value. Value should already be persisted to
 // disk.  A racing delete can trigger a failure where we get a null return,
 // but no crash (although one could argue that a racing load&delete is a bug
 // no matter what).
 @Override
 public byte[] load(Value v) {
   long skip = 0;
   Key k = v._key;
   // Convert an arraylet chunk into a long-offset from the base file.
   if (k._kb[0] == Key.ARRAYLET_CHUNK) {
     skip = ValueArray.getChunkOffset(k); // The offset
     k = ValueArray.getArrayKey(k); // From the base file key
   }
   if (k._kb[0] == Key.DVEC) {
     skip = water.fvec.NFSFileVec.chunkOffset(k); // The offset
   }
   try {
     FileInputStream s = null;
     try {
       s = new FileInputStream(getFileForKey(k));
       FileChannel fc = s.getChannel();
       fc.position(skip);
       AutoBuffer ab = new AutoBuffer(fc, true, Value.NFS);
       byte[] b = ab.getA1(v._max);
       ab.close();
       assert v.isPersisted();
       return b;
     } finally {
       if (s != null) s.close();
     }
   } catch (IOException e) { // Broken disk / short-file???
     H2O.ignore(e);
     return null;
   }
 }
Exemplo n.º 9
0
 public MappedFileDataInput(
     FileInputStream stream, String filename, long segmentOffset, int position)
     throws IOException {
   FileChannel channel = stream.getChannel();
   buffer = channel.map(FileChannel.MapMode.READ_ONLY, position, channel.size());
   this.filename = filename;
   this.segmentOffset = segmentOffset;
   this.position = position;
 }
Exemplo n.º 10
0
 public InputStream getInputStream() throws IOException {
   FileInputStream fis = new FileInputStream(getFile());
   FileChannel fc = fis.getChannel();
   ByteBuffer bb = ByteBuffer.allocateDirect((int) size);
   fc.read(bb, position);
   fc.close();
   fc = null;
   fis.close();
   fis = null;
   return new ByteBufferInputStream(bb);
 }
  private byte[] loadClassData(String name) throws IOException {
    FileInputStream f = new FileInputStream("CrashClass.class");
    int size = (int) f.getChannel().size();
    DataInputStream s = new DataInputStream(f);

    byte[] b = new byte[size];
    s.readFully(b);
    s.close();

    return b;
  }
  /**
   * Closes the stream, moving the written contents to the streams destination file. This will copy
   * the contents of the underlying temp file and remove it.
   *
   * @throws IOException
   */
  public void close() throws IOException {
    _outStream.close();

    final FileOutputStream out = new FileOutputStream(_file);
    final FileInputStream in = new FileInputStream(_tempFile);

    in.getChannel().transferTo(0, _tempFile.length(), out.getChannel());
    out.close();
    in.close();
    if (!_tempFile.delete()) _tempFile.deleteOnExit();
  }
Exemplo n.º 13
0
 public static void copyFile(File source, File dest) throws IOException {
   FileInputStream fi = new FileInputStream(source);
   FileChannel fic = fi.getChannel();
   MappedByteBuffer mbuf = fic.map(FileChannel.MapMode.READ_ONLY, 0, source.length());
   fic.close();
   fi.close();
   FileOutputStream fo = new FileOutputStream(dest);
   FileChannel foc = fo.getChannel();
   foc.write(mbuf);
   foc.close();
   fo.close();
 }
Exemplo n.º 14
0
  @Test
  public void serializing() throws Exception {
    // grab a new scan
    MsnSpectrum[] scans = firstScan(root + "20081129_Orbi6_NaNa_SA_FASP_blacktips_01.mzXML", 2, 2);
    MsnSpectrum scan = scans[0], scan2 = scans[1];

    FileOutputStream f_out = new FileOutputStream("/tmp/myobject.data");

    // Write object with ObjectOutputStream
    ObjectOutputStream obj_out = new ObjectOutputStream(f_out);

    // Write object out to disk
    long p1 = f_out.getChannel().position();
    obj_out.writeObject(MsSpectrum.adopt(scan));
    long p2 = f_out.getChannel().position();
    obj_out.writeObject(MsSpectrum.adopt(scan2));

    obj_out.close();
    f_out.close();

    FileInputStream f_in = new FileInputStream("/tmp/myobject.data");

    ObjectInputStream obj_in = new ObjectInputStream(f_in);
    MsSpectrum m1 = (MsSpectrum) obj_in.readObject();
    obj_in.close();
    f_in.close();

    f_in = new FileInputStream("/tmp/myobject.data");
    obj_in = new ObjectInputStream(f_in);

    f_in.getChannel().position(p1);
    //    MsSpectrum m3 = (MsSpectrum )obj_in.readObject();
    f_in.getChannel().position(p2);
    long p3 = f_in.getChannel().position();

    MsSpectrum m4 = (MsSpectrum) obj_in.readObject();
    obj_in.close();
    f_in.close();
  }
Exemplo n.º 15
0
  public void mergeInto(OutputStream targetStream) {
    FileInputStream sourceStream = null;
    try {
      sourceStream = new FileInputStream(file);
      FileChannel sourceChannel = sourceStream.getChannel();

      WritableByteChannel targetChannel = Channels.newChannel(targetStream);
      sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);

      sourceStream.close();
      file.delete();
    } catch (FileNotFoundException ex) {
      throw new UserException.CouldNotReadInputFile(
          file, "Unable to open input stream for file", ex);
    } catch (IOException ex) {
      throw new UserException.CouldNotReadInputFile(
          file, "Unable to transfer contents of file", ex);
    }
  }
Exemplo n.º 16
0
  public static void main(String args[]) throws Exception {
    FileInputStream fin = new FileInputStream("readandshow.txt");
    FileChannel fc = fin.getChannel();

    ByteBuffer buffer = ByteBuffer.allocate(1024);

    fc.read(buffer);

    buffer.flip();

    int i = 0;
    while (buffer.remaining() > 0) {
      byte b = buffer.get();
      System.out.println("Character " + i + ": " + ((char) b));
      i++;
    }

    fin.close();
  }
Exemplo n.º 17
0
  public static void main(String[] args) throws Exception {

    File blah = File.createTempFile("blah", null);
    blah.deleteOnExit();
    ByteBuffer[] dstBuffers = new ByteBuffer[10];
    for (int i = 0; i < 10; i++) {
      dstBuffers[i] = ByteBuffer.allocateDirect(10);
      dstBuffers[i].position(10);
    }
    FileInputStream fis = new FileInputStream(blah);
    FileChannel fc = fis.getChannel();

    // No space left in buffers, this should return 0
    long bytesRead = fc.read(dstBuffers);
    if (bytesRead != 0) throw new RuntimeException("Nonzero return from read");

    fc.close();
    fis.close();
  }
Exemplo n.º 18
0
 public static void fileChannelCopy(File s, File t) {
   FileInputStream fi = null;
   FileOutputStream fo = null;
   try {
     fi = new FileInputStream(s);
     fo = new FileOutputStream(t);
     FileChannel in = fi.getChannel(); // 得到对应的文件通道
     FileChannel out = fo.getChannel(); // 得到对应的文件通道
     in.transferTo(0, in.size(), out); // 连接两个通道,并且从in通道读取,然后写入out通道
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     try {
       if (fo != null) fo.close();
       if (fi != null) fi.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }
Exemplo n.º 19
0
  public static void copyFileNIO(String filenameIn, String filenameOut, long kbchunks)
      throws IOException {

    FileInputStream in = new FileInputStream(filenameIn);
    FileChannel inChannel = in.getChannel();

    FileOutputStream out = new FileOutputStream(filenameOut);
    FileChannel outChannel = out.getChannel();

    long size = inChannel.size();
    // outChannel.position(size-2);
    // outChannel.write(ByteBuffer.allocate(1));
    // outChannel.position(0);

    if (debug)
      System.out.println(
          "read " + filenameIn + " len = " + size + " out starts at=" + outChannel.position());

    long start = System.currentTimeMillis();
    long done = 0;
    while (done < size) {
      long need = Math.min(kbchunks * 1000, size - done);
      done += inChannel.transferTo(done, need, outChannel);
    }

    outChannel.close();
    inChannel.close();

    double took = .001 * (System.currentTimeMillis() - start);
    if (debug) System.out.println(" write file= " + filenameOut + " len = " + size);

    double rate = size / took / (1000 * 1000);
    System.out.println(
        " copyFileNIO("
            + kbchunks
            + " kb chunk) took = "
            + took
            + " sec; rate = "
            + rate
            + "Mb/sec");
  }
Exemplo n.º 20
0
  /**
   * Extracts the raw ID3v2 tag data into a file.
   *
   * <p>This provides access to the raw data before manipulation, the data is written from the start
   * of the file to the start of the Audio Data. This is primarily useful for manipulating corrupted
   * tags that are not (fully) loaded using the standard methods.
   *
   * @param outputFile to write the data to
   * @return
   * @throws TagNotFoundException
   * @throws IOException
   */
  public File extractID3v2TagDataIntoFile(File outputFile)
      throws TagNotFoundException, IOException {
    int startByte = (int) ((MP3AudioHeader) audioHeader).getMp3StartByte();
    if (startByte >= 0) {

      // Read byte into buffer
      FileInputStream fis = new FileInputStream(file);
      FileChannel fc = fis.getChannel();
      ByteBuffer bb = ByteBuffer.allocate(startByte);
      fc.read(bb);

      // Write bytes to outputFile
      FileOutputStream out = new FileOutputStream(outputFile);
      out.write(bb.array());
      out.close();
      fc.close();
      fis.close();
      return outputFile;
    }
    throw new TagNotFoundException("There is no ID3v2Tag data in this file");
  }
Exemplo n.º 21
0
  private boolean loadBaseAndCheckByFileChannel(String path) {
    try {
      FileInputStream fis = new FileInputStream(path);
      // 1.从FileInputStream对象获取文件通道FileChannel
      FileChannel channel = fis.getChannel();
      int fileSize = (int) channel.size();

      // 2.从通道读取文件内容
      ByteBuffer byteBuffer = ByteBuffer.allocate(fileSize);

      // channel.read(ByteBuffer) 方法就类似于 inputstream.read(byte)
      // 每次read都将读取 allocate 个字节到ByteBuffer
      channel.read(byteBuffer);
      // 注意先调用flip方法反转Buffer,再从Buffer读取数据
      byteBuffer.flip();
      // 有几种方式可以操作ByteBuffer
      // 可以将当前Buffer包含的字节数组全部读取出来
      byte[] bytes = byteBuffer.array();
      byteBuffer.clear();
      // 关闭通道和文件流
      channel.close();
      fis.close();

      int index = 0;
      size = ByteUtil.bytesHighFirstToInt(bytes, index);
      index += 4;
      base = new int[size + 65535]; // 多留一些,防止越界
      check = new int[size + 65535];
      for (int i = 0; i < size; i++) {
        base[i] = ByteUtil.bytesHighFirstToInt(bytes, index);
        index += 4;
        check[i] = ByteUtil.bytesHighFirstToInt(bytes, index);
        index += 4;
      }
    } catch (Exception e) {
      return false;
    }
    return true;
  }
Exemplo n.º 22
0
 public String getFileContents(String fileName) throws APIException {
   if ((new File(fileName)).exists()) {
     FileInputStream stream = null;
     try {
       stream = new FileInputStream(new File(fileName));
       FileChannel fc = stream.getChannel();
       MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
       /* Instead of using default, pass in a decoder. */
       return Charset.forName("UTF-8").decode(bb).toString();
     } catch (Exception e) {
       throw new APIException(fileName + " could not have its files extracte!");
     } finally {
       try {
         stream.close();
       } catch (Exception e) {
         throw new APIException(fileName + " could not be closed!");
       }
     }
   } else {
     throw new APIException(fileName + " doesn't exist!");
   }
 }
Exemplo n.º 23
0
  /**
   * Internal copy file method.
   *
   * @param srcFile the validated source file, must not be <code>null</code>
   * @param destFile the validated destination file, must not be <code>null</code>
   * @param preserveFileDate whether to preserve the file date
   * @throws IOException if an error occurs
   */
  private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate)
      throws IOException {
    if (destFile.exists() && destFile.isDirectory()) {
      throw new IOException("Destination '" + destFile + "' exists but is a directory");
    }
    if (!srcFile.exists()) {
      throw new IOException("Source file '" + srcFile + "' does not exist");
    }
    FileInputStream fis = null;
    FileOutputStream fos = null;
    FileChannel input = null;
    FileChannel output = null;
    try {
      fis = new FileInputStream(srcFile);
      fos = new FileOutputStream(destFile);
      input = fis.getChannel();
      output = fos.getChannel();
      long size = input.size();
      long pos = 0;
      long count = 0;
      while (pos < size) {
        count = (size - pos) > FIFTY_MB ? FIFTY_MB : (size - pos);
        pos += output.transferFrom(input, pos, count);
      }
    } finally {
      closeQuietly(output);
      closeQuietly(fos);
      closeQuietly(input);
      closeQuietly(fis);
    }

    if (srcFile.length() != destFile.length()) {
      throw new IOException(
          "Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'");
    }
    if (preserveFileDate) {
      destFile.setLastModified(srcFile.lastModified());
    }
  }
Exemplo n.º 24
0
  /** Lis le header du fichier temporaire et charge ses informations */
  private void readHeaderTmpFile() {
    try {
      FileInputStream reader_tmp = new FileInputStream(this);
      FileChannel reader = reader_tmp.getChannel();

      int key_size = 0;
      int offset = 0;

      // Taile de le clef
      key_size = Tools.readInt(reader, offset);
      offset += 4;
      // Clef
      _key = Tools.readString(reader, offset, key_size);
      offset += key_size;
      // Size
      _size = Tools.readInt(reader, offset);
      offset += 4;
      // piecesize
      _piecesize = Tools.readInt(reader, offset);
      offset += 4;
      // Buffermap
      _buffermap = new Buffermap(this.nbPieces(), false);
      int i;
      for (i = 0; i < this.nbPieces(); i++) {
        int index = Tools.readInt(reader, offset);
        if (index >= 0) {
          _buffermap.setBit(i, true);
        } else {
          _buffermap.setBit(i, false);
        }
        offset += 4;
      }

      reader_tmp.close();
    } catch (Exception e) {
      System.out.println("Unable to read tmp file header");
      e.printStackTrace();
    }
  }
Exemplo n.º 25
0
  public static void main(String[] args) throws MalformedURLException, Exception {
    AndoAPieSpider app = new AndoAPieSpider();

    String url =
        "http://www.rutasjalisco.gob.mx/rutas-por-empresas-de-transporte/red-parapanamericana/";
    int arg1 = 0;
    int arg2 = 0;
    int arg3 = 0;

    String[] fl = url.split("/");
    File file = new File("urls_" + fl[fl.length - 1] + ".txt");
    System.out.print("Buscando archivo " + file.getAbsolutePath() + " ... ");
    if (file.exists()) {
      System.out.println("Econtrado!");
      FileInputStream stream = new FileInputStream(file);
      FileChannel fc = stream.getChannel();
      MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
      app.getKMLs(Charset.defaultCharset().decode(bb).toString().split("\n"));
      stream.close();
    } else {
      System.out.println("no se encontro, obteniendo urls!");
      app.runAll(url, arg1, arg2, arg3, file.getAbsolutePath());
    }
  }
Exemplo n.º 26
0
  /**
   * Lis et retourne une pièce depuis le fichier complet sur le disque
   *
   * @param num : numéros de la piece
   */
  private byte[] readPieceCompleteFile(int num) {
    if (num < 0 || num >= this.nbPieces()) {
      throw new IllegalArgumentException();
    }

    try {
      FileInputStream reader_tmp = new FileInputStream(this);
      FileChannel reader = reader_tmp.getChannel();

      int size = _piecesize;
      if (num == this.nbPieces() - 1) {
        size = _size - _piecesize * (this.nbPieces() - 1);
      }

      byte[] piece = Tools.readBytes(reader, _piecesize * num, size);
      reader_tmp.close();

      return piece;
    } catch (Exception e) {
      System.out.println("Unable to read complete file piece");
      e.printStackTrace();
    }
    return new byte[0];
  }
Exemplo n.º 27
0
  /** In case of interrupted, written file is not deleted. */
  private void copyFile(File sourceFile, File destFile, Reporter reporter)
      throws IOException, InterruptedException {
    if (!destFile.exists()) {
      destFile.createNewFile();
    }
    FileChannel source = null;
    FileChannel destination = null;

    Throttler throttler = new Throttler((double) bytesPerSecThrottle);

    FileInputStream iS = null;
    FileOutputStream oS = null;

    try {
      iS = new FileInputStream(sourceFile);
      oS = new FileOutputStream(destFile);
      source = iS.getChannel();
      destination = oS.getChannel();
      long bytesSoFar = 0;
      long reportingBytesSoFar = 0;
      long size = source.size();

      int transferred = 0;

      while (bytesSoFar < size) {
        // Needed to being able to be interrupted at any moment.
        if (Thread.interrupted()) {
          throw new InterruptedException();
        }

        // Casting to int here is safe since we will transfer at most "downloadBufferSize" bytes.
        // This is done on purpose for being able to implement Throttling.
        transferred = (int) destination.transferFrom(source, bytesSoFar, downloadBufferSize);
        bytesSoFar += transferred;
        reportingBytesSoFar += transferred;
        throttler.incrementAndThrottle(transferred);
        if (reportingBytesSoFar >= bytesToReportProgress) {
          reporter.progress(reportingBytesSoFar);
          reportingBytesSoFar = 0l;
        }
      }

      if (reporter != null) {
        reporter.progress(reportingBytesSoFar);
      }

    } catch (InterruptedException e) {
      e.printStackTrace();
    } finally {
      if (iS != null) {
        iS.close();
      }
      if (oS != null) {
        oS.close();
      }
      if (source != null) {
        source.close();
      }
      if (destination != null) {
        destination.close();
      }
    }
  }
Exemplo n.º 28
0
  /**
   * Read V2tag if exists
   *
   * <p>TODO:shouldn't we be handing TagExceptions:when will they be thrown
   *
   * @param file
   * @param loadOptions
   * @throws IOException
   * @throws TagException
   */
  private void readV2Tag(File file, int loadOptions, int startByte)
      throws IOException, TagException {
    // We know where the actual Audio starts so load all the file from start to that point into
    // a buffer then we can read the IDv2 information without needing any more File I/O
    if (startByte >= AbstractID3v2Tag.TAG_HEADER_LENGTH) {
      logger.finer("Attempting to read id3v2tags");
      FileInputStream fis = null;
      FileChannel fc = null;
      ByteBuffer bb;
      try {
        fis = new FileInputStream(file);
        fc = fis.getChannel();
        bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, startByte);
      }
      // #JAUDIOTAGGER-419:If reading networked file map can fail so just copy bytes instead
      catch (IOException ioe) {
        bb = ByteBuffer.allocate(startByte);
        fc.read(bb, 0);
      } finally {
        if (fc != null) {
          fc.close();
        }

        if (fis != null) {
          fis.close();
        }
      }

      try {
        bb.rewind();

        if ((loadOptions & LOAD_IDV2TAG) != 0) {
          logger.config("Attempting to read id3v2tags");
          try {
            this.setID3v2Tag(new ID3v24Tag(bb, file.getName()));
          } catch (TagNotFoundException ex) {
            logger.config("No id3v24 tag found");
          }

          try {
            if (id3v2tag == null) {
              this.setID3v2Tag(new ID3v23Tag(bb, file.getName()));
            }
          } catch (TagNotFoundException ex) {
            logger.config("No id3v23 tag found");
          }

          try {
            if (id3v2tag == null) {
              this.setID3v2Tag(new ID3v22Tag(bb, file.getName()));
            }
          } catch (TagNotFoundException ex) {
            logger.config("No id3v22 tag found");
          }
        }
      } finally {
        // Workaround for 4724038 on Windows
        bb.clear();
        if (bb.isDirect() && !TagOptionSingleton.getInstance().isAndroid()) {
          // Reflection substitute for following code:
          //    ((sun.nio.ch.DirectBuffer) bb).cleaner().clean();
          // which causes exception on Android - Sun NIO classes are not available
          try {
            Class<?> clazz = Class.forName("sun.nio.ch.DirectBuffer");
            Method cleanerMethod = clazz.getMethod("cleaner");
            Object cleaner = cleanerMethod.invoke(bb); // cleaner = bb.cleaner()
            if (cleaner != null) {
              Method cleanMethod = cleaner.getClass().getMethod("clean");
              cleanMethod.invoke(cleaner); // cleaner.clean()
            }
          } catch (ClassNotFoundException e) {
            logger.severe("Could not load sun.nio.ch.DirectBuffer.");
          } catch (NoSuchMethodException e) {
            logger.severe("Could not invoke DirectBuffer method - " + e.getMessage());
          } catch (InvocationTargetException e) {
            logger.severe("Could not invoke DirectBuffer method - target exception");
          } catch (IllegalAccessException e) {
            logger.severe("Could not invoke DirectBuffer method - illegal access");
          }
        }
      }
    } else {
      logger.config("Not enough room for valid id3v2 tag:" + startByte);
    }
  }
Exemplo n.º 29
0
  public static void main(String[] argv) {
    if (argv.length != 3) {
      usage();
    }

    String tempFile = argv[0];
    String testFile = argv[1];
    int fileSize = Integer.valueOf(argv[2]).intValue();
    int exitcode = 0;
    int numRead;
    int numThisBuf;
    int numWritten;

    if ((fileSize <= 0) || (fileSize % 4096 != 0)) {
      System.out.println("Error: size is not a multiple of 4096!!!!!!");
      System.out.println();
      usage();
    }

    try {
      int bufSize = 4096;
      byte[] inBytes = new byte[bufSize];
      byte[] outBytes = new byte[bufSize];
      Random ioRandom = new Random(2006);
      ioRandom.nextBytes(outBytes);
      ByteBuffer inBuf = ByteBuffer.allocate(bufSize);
      ByteBuffer outBuf = ByteBuffer.wrap(outBytes);

      //
      // Loop forever
      //
      while (true) {
        //
        // Write the temporary file
        //
        FileOutputStream fos = new FileOutputStream(tempFile);
        FileChannel foc = fos.getChannel();
        numWritten = 0;
        while (numWritten < fileSize) {
          outBuf.clear(); // sets limit to capacity & position to zero
          while (outBuf.hasRemaining()) {
            numWritten += foc.write(outBuf);
          }
        }

        //
        // Move to permanent location
        //
        FileChannel srcChannel = new FileInputStream(tempFile).getChannel();
        FileChannel dstChannel = new FileOutputStream(testFile).getChannel();
        dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
        srcChannel.close();
        dstChannel.close();
        boolean success = (new File(tempFile)).delete();
        if (!success) {
          System.out.println("Warning: unable to delete temporary file");
        }

        //
        // Read and compare
        //
        FileInputStream fis = new FileInputStream(testFile);
        FileChannel fic = fis.getChannel();

        for (numRead = 0, numThisBuf = 0; numRead < fileSize; numThisBuf = 0) {
          inBuf.rewind(); // Set the buffer position to 0
          numThisBuf = fic.read(inBuf);
          while (numThisBuf < bufSize) {
            numThisBuf += fic.read(inBuf);
          }
          numRead += bufSize;
          inBuf.rewind(); // Set the buffer position to 0
          inBuf.get(inBytes);
          boolean same = Arrays.equals(inBytes, outBytes);
          if (same = false) {
            System.out.println("Data read does not equal data written at " + numRead + " bytes");
          }
        }
      }

    } catch (FileNotFoundException fnfe) {
      fnfe.printStackTrace(System.err);
      exitcode = 1;
      // break;
    } catch (SecurityException se) {
      se.printStackTrace(System.err);
      exitcode = 1;
      // break;
    } catch (Throwable t) {
      t.printStackTrace(System.err);
      exitcode = 1;
    }

    System.exit(exitcode);
  }
Exemplo n.º 30
0
 private void readFromFile(File file) throws IOException {
   fis = new FileInputStream(file);
   chan = fis.getChannel();
   ByteBuffer buf = chan.map(FileChannel.MapMode.READ_ONLY, 0, (int) file.length());
   readFromBuffer(buf);
 }