Example #1
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 ");
  }
  public static long checksumMappedFile(Path filename) throws IOException {
    try (FileChannel channel = FileChannel.open(filename)) {
      CRC32 crc = new CRC32();
      int length = (int) channel.size();
      MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, length);

      for (int p = 0; p < length; p++) {
        int c = buffer.get(p);
        crc.update(c);
      }
      return crc.getValue();
    }
  }
  /**
   * Decode file charset.
   *
   * @param f File to process.
   * @return File charset.
   * @throws IOException in case of error.
   */
  public static Charset decode(File f) throws IOException {
    SortedMap<String, Charset> charsets = Charset.availableCharsets();

    String[] firstCharsets = {
      Charset.defaultCharset().name(), "US-ASCII", "UTF-8", "UTF-16BE", "UTF-16LE"
    };

    Collection<Charset> orderedCharsets = U.newLinkedHashSet(charsets.size());

    for (String c : firstCharsets)
      if (charsets.containsKey(c)) orderedCharsets.add(charsets.get(c));

    orderedCharsets.addAll(charsets.values());

    try (RandomAccessFile raf = new RandomAccessFile(f, "r")) {
      FileChannel ch = raf.getChannel();

      ByteBuffer buf = ByteBuffer.allocate(4096);

      ch.read(buf);

      buf.flip();

      for (Charset charset : orderedCharsets) {
        CharsetDecoder decoder = charset.newDecoder();

        decoder.reset();

        try {
          decoder.decode(buf);

          return charset;
        } catch (CharacterCodingException ignored) {
        }
      }
    }

    return Charset.defaultCharset();
  }