Java 类java.nio.channels.Channels 实例源码

项目:annoflex    文件:SystemToolkit.java   
/**
 * 
 */
public static byte[] readBytes(File file) throws IOException {
    if (file != null) {
        long fileSize = file.length();

        if (fileSize > MAX_ARRAY_SIZE) {
            throw new IOException("file is too large");
        }

        try (SeekableByteChannel byteChannel = Files.newByteChannel(file.toPath());
                InputStream inputStream = Channels.newInputStream(byteChannel)) {

            int available = inputStream.available();

            if (available > 0) {
                return readBytes(inputStream,available > fileSize ?
                        available : (int)fileSize);
            }
        }
    }

    return EMPTY_BYTE_ARRAY;
}
项目:MaxSim    文件:Parser.java   
@Override
public GraphDocument parse() throws IOException {
    if (monitor != null) {
        monitor.setState("Starting parsing");
    }
    try {
        XMLReader reader = createReader();
        reader.setContentHandler(new XMLParser(xmlDocument, monitor));
        reader.parse(new InputSource(Channels.newInputStream(channel)));
    } catch (SAXException ex) {
        if (!(ex instanceof SAXParseException) || !"XML document structures must start and end within the same entity.".equals(ex.getMessage())) {
            throw new IOException(ex);
        }
    }
    if (monitor != null) {
        monitor.setState("Finished parsing");
    }
    return graphDocument;
}
项目:cornerstone    文件:IOUtils.java   
public static byte[] partitionRead(final Path path,int partionSize,int partitionIndex) throws IOException {

        try (SeekableByteChannel sbc = Files.newByteChannel(path);
             InputStream in = Channels.newInputStream(sbc)) {
            long startIndex = (partitionIndex-1)*partionSize;
            if (startIndex < 0) {
                startIndex = 0;
            }
            in.skip(startIndex);
            if (partionSize >  MAX_BUFFER_SIZE)
                throw new OutOfMemoryError("Required array size too large");

            return read(in,  partionSize);

        }
    }
项目:alfresco-repository    文件:AbstractContentWriter.java   
/**
 * @see Channels#newOutputStream(java.nio.channels.WritableByteChannel)
 */
public OutputStream getContentOutputStream() throws ContentIOException
{
    try
    {
        WritableByteChannel channel = getWritableChannel();
        OutputStream is = new BufferedOutputStream(Channels.newOutputStream(channel));
        // done
        return is;
    }
    catch (Throwable e)
    {
        throw new ContentIOException("Failed to open stream onto channel: \n" +
                "   writer: " + this,
                e);
    }
}
项目:CDN-FX-2.2    文件:Updater.java   
public boolean update(){
    try{
        DebugLogger.log("Updating...", Level.INFO);
        String path = Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
        ReadableByteChannel in = Channels.newChannel(new URL(updateURL + "gfx.jar").openStream());
        FileChannel out = new FileOutputStream(path).getChannel();

        out.transferFrom(in, 0, Long.MAX_VALUE);
        in.close();
        out.close();

        DebugLogger.log("Update successful!", Level.INFO);
        return true;

    }catch(Exception e){
        DebugLogger.log("Update failed!", Level.INFO);
        return false;
    }
}
项目:httrack2warc    文件:NdxCache.java   
private void parseDatHeader() throws IOException {
    if (parsed) return;
    try (SeekableByteChannel channel = Files.newByteChannel(datFile)) {
        channel.position(Math.abs(position));
        CountingStream countingStream = new CountingStream(new BufferedInputStream(Channels.newInputStream(channel)), Long.MAX_VALUE);
        DataInputStream stream = new DataInputStream(countingStream);
        String status = readString(stream);
        String size = readString(stream);
        String msg = readString(stream);
        String contentType = readString(stream);
        String lastModified = readString(stream);
        String etag = readString(stream);

        for (;;) {
            String line = readString(stream);
            if (line.equals("HTS")) break;
            if (line.equals("SD")) {
                readString(stream); // supplementary data
            }
        }

        dataLen = Long.parseLong(readString(stream));
        headerLen = countingStream.count;
        parsed = true;
    }
}
项目:curiostack    文件:CloudStorageBuildCacheService.java   
@Override
public boolean load(BuildCacheKey buildCacheKey, BuildCacheEntryReader buildCacheEntryReader)
    throws BuildCacheException {
  try {
    Blob blob = cloudStorage.get(cacheKeyToBlobId(buildCacheKey));
    if (blob == null || !blob.exists()) {
      return false;
    }
    try (InputStream is = Channels.newInputStream(blob.reader())) {
      buildCacheEntryReader.readFrom(is);
    }
  } catch (Exception e) {
    logger.warn(
        "Exception when trying to read from cloud storage, this usually means gcloud "
            + "auth application-default login has not been called. Builds may be slower.",
        e);
    return false;
  }
  return true;
}
项目:chromium-net-for-android    文件:JavaUrlRequest.java   
void startRead() {
    mExecutor.execute(errorSetting(State.STARTED, new CheckedRunnable() {
        @Override
        public void run() throws Exception {
            if (mOutputChannel == null) {
                mAdditionalStatusDetails = Status.CONNECTING;
                mUrlConnection.connect();
                mAdditionalStatusDetails = Status.SENDING_REQUEST;
                mOutputChannel = Channels.newChannel(mUrlConnection.getOutputStream());
            }
            mSinkState.set(SinkState.AWAITING_READ_RESULT);
            mUserExecutor.execute(uploadErrorSetting(new CheckedRunnable() {
                @Override
                public void run() throws Exception {
                    mUploadProvider.read(OutputStreamDataSink.this, mBuffer);
                }
            }));
        }
    }));
}
项目:Motunautr    文件:Settings.java   
public static void load() throws IOException {
        final File folder = new File(System.getProperty("user.home") + "/AppData/Roaming/Motunautr/");
        folder.mkdirs();
        final File file = new File(folder, "settings.properties");
        @SuppressWarnings("resource") // deliberately not closed 
        final RandomAccessFile settingsFile = new RandomAccessFile(file, "rw");
//      Settings.settingsFile = settingsFile;
        openChannel = settingsFile.getChannel();
        lock = openChannel.tryLock();
        if (lock == null) {
            JOptionPane.showMessageDialog(null, "Motunautr is already running!", "Error", JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }
        if (settingsFile.length() == 0)
            Main.isFirstRun = true;
        INSTANCE.load(Channels.newReader(openChannel, "utf-8"));
    }
项目:CDN-FX-2.2    文件:XMLUpdater.java   
public boolean update(){
    try{
        DebugLogger.log("Updating XML...", Level.INFO);
        String path = Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
        path = path.substring(1, path.lastIndexOf("/")) + "/";
        ReadableByteChannel in = Channels.newChannel(new URL(updateURL + "community.xml").openStream());
        FileChannel out = new FileOutputStream((path+"community.xml")).getChannel();

        out.transferFrom(in, 0, Long.MAX_VALUE);
        in.close();
        out.close();

        DebugLogger.log("XML Update successful!", Level.INFO);
        return true;

    }catch(Exception e){
        DebugLogger.log("XML Update failed!", Level.INFO);
        return false;
    }
}
项目:gnirehtet    文件:StreamBufferTest.java   
@Test
public void testNotEnoughSpace() throws IOException {
    ByteBuffer buffer = createChunk();

    StreamBuffer streamBuffer = new StreamBuffer(9);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    WritableByteChannel channel = Channels.newChannel(bos);

    streamBuffer.readFrom(buffer);
    buffer.rewind();
    streamBuffer.readFrom(buffer);

    Assert.assertEquals(3, buffer.remaining());

    streamBuffer.writeTo(channel);

    byte[] result = bos.toByteArray();
    byte[] expected = {0, 1, 2, 3, 4, 5, 0, 1, 2};
    Assert.assertArrayEquals(expected, result);
}
项目:n5    文件:N5FSWriter.java   
@Override
public void setAttributes(
        final String pathName,
        final Map<String, ?> attributes) throws IOException {

    final Path path = Paths.get(basePath, getAttributesPath(pathName).toString());
    final HashMap<String, JsonElement> map = new HashMap<>();

    try (final LockedFileChannel lockedFileChannel = LockedFileChannel.openForWriting(path)) {
        map.putAll(GsonAttributesParser.readAttributes(Channels.newReader(lockedFileChannel.getFileChannel(), StandardCharsets.UTF_8.name()), getGson()));
        GsonAttributesParser.insertAttributes(map, attributes, gson);

        lockedFileChannel.getFileChannel().truncate(0);
        GsonAttributesParser.writeAttributes(Channels.newWriter(lockedFileChannel.getFileChannel(), StandardCharsets.UTF_8.name()), map, getGson());
    }
}
项目:omero-ms-queue    文件:FileOps.java   
/**
 * Efficiently copies an initial segment of a file into a target stream.
 * @param from path to the file from which to get the data.
 * @param howManyBytes number of bytes to take, starting at the beginning
 * of the file.
 * @param to where to copy the data.
 * @return the number of bytes actually copied.
 * @throws NullPointerException if any argument is {@code null}.
 * @throws IOException if an I/O error occurs.
 */
public static long transfer(Path from, Nat howManyBytes, OutputStream to) 
        throws IOException {
    requireNonNull(from, "from");
    requireNonNull(howManyBytes, "howManyBytes");
    requireNonNull(to, "to");

    try (FileChannel source = FileChannel.open(from);
         WritableByteChannel target = Channels.newChannel(to)) {
        long limit = howManyBytes.get();
        long bytesRead = 0;
        while (bytesRead < limit && bytesRead < source.size()) {  // (1)
            long count = limit - bytesRead;
            bytesRead += source.transferTo(bytesRead, count, target); // (2)
        }
        return bytesRead;
    }
}
项目:LD38    文件:Util.java   
public static ByteBuffer ioResourceToByteBuffer(String resource, int bufferSize) throws IOException {
    ByteBuffer buffer;

    Path path = Paths.get(resource);
    if(Files.isReadable(path)) {
        try(SeekableByteChannel fc = Files.newByteChannel(path)){
            buffer = BufferUtils.createByteBuffer((int)fc.size() + 1);
            while(fc.read(buffer) != -1);
        }
    }else{
        try(InputStream source = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource);
            ReadableByteChannel rbc = Channels.newChannel(source)){
            buffer = BufferUtils.createByteBuffer(bufferSize);
            while(true){
                int bytes = rbc.read(buffer);
                if(bytes == -1)
                    break;
                if (buffer.remaining() == 0)
                    buffer = resizeBuffer(buffer, buffer.capacity() * 2);
            }
        }
    }

    buffer.flip();
    return buffer;
}
项目:xm-lep    文件:StringUtils.java   
/**
 * Generates text preview.
 *
 * @param is               original text input stream
 * @param encoding         input stream encoding
 * @param linesCount       preview lines count
 * @param ignoreEmptyLines flag to ignore blank lines while counting preview
 * @param maxLength        max char length for preview (can be  {@code null} if this restriction is not needed)
 * @return text preview string
 */
public static String getPreview(InputStream is, String encoding, int linesCount, boolean ignoreEmptyLines,
                                Integer maxLength) {
    if (maxLength != null && maxLength < 0) {
        throw new IllegalArgumentException("maxLength can't be negative");
    }

    if (is == null) {
        return "<null>";
    }

    if (linesCount <= 0) {
        return "";
    }

    ReadableByteChannel readableChannel = Channels.newChannel(is);
    Scanner scanner = new Scanner(readableChannel, encoding);
    return getPreview(linesCount, ignoreEmptyLines, maxLength, scanner);
}
项目:Shuriken    文件:URLClassLoaderToolsTester.java   
private Path downloadTestJar() throws Exception {
    /* aopalliance library for test, hopefully this won't disappear */
    String url = "https://repo.maven.apache.org/maven2/aopalliance/aopalliance/1.0/aopalliance-1.0.jar";

    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    Path file = Files.createTempFile("testlib", ".jar");
    try(FileChannel fc = new FileOutputStream(file.toFile()).getChannel()) {
        fc.transferFrom(
                Channels.newChannel(connection.getInputStream()),
                0,
                Long.MAX_VALUE
        );
    }

    return file;
}
项目:googles-monorepo-demo    文件:ByteStreamsTest.java   
public void testCopyFileChannel() throws IOException {
  final int chunkSize = 14407; // Random prime, unlikely to match any internal chunk size
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  WritableByteChannel outChannel = Channels.newChannel(out);

  File testFile = createTempFile();
  FileOutputStream fos = new FileOutputStream(testFile);
  byte[] dummyData = newPreFilledByteArray(chunkSize);
  try {
    for (int i = 0; i < 500; i++) {
      fos.write(dummyData);
    }
  } finally {
    fos.close();
  }
  ReadableByteChannel inChannel = new RandomAccessFile(testFile, "r").getChannel();
  try {
    ByteStreams.copy(inChannel, outChannel);
  } finally {
    inChannel.close();
  }
  byte[] actual = out.toByteArray();
  for (int i = 0; i < 500 * chunkSize; i += chunkSize) {
    assertEquals(dummyData, Arrays.copyOfRange(actual, i, i + chunkSize));
  }
}
项目:candlelight    文件:BitmapLoader.java   
@Override
public Bitmap load(InputStream stream) throws Exception
{
    ByteBuffer buffer = BufferUtils.createByteBuffer(256);
    try (ReadableByteChannel channel = Channels.newChannel(stream))
    {
        while (channel.read(buffer) != -1)
        {
            if (buffer.remaining() == 0)
            {
                buffer = resizeBuffer(buffer, buffer.capacity() * 2);
            }
        }
    }
    buffer.flip();

    return new Bitmap(buffer, false, false);
}
项目:iosched-reader    文件:APIExtractor.java   
public void run(OutputStream optionalOutput, boolean extractUnpublished) throws IOException {
  // fill sources with extra input:
  JsonDataSources sources = new ExtraInput().fetchAllDataSources();
  // fill sources with vendor API input:
  VendorDynamicInput vendorInput = new VendorDynamicInput();
  vendorInput.setExtractUnpublished(extractUnpublished);
  sources.putAll(vendorInput.fetchAllDataSources());
  // extract session data from inputs:
  JsonObject newData = new DataExtractor(false).extractFromDataSources(sources);

  // send data to the outputstream
  Writer writer = Channels.newWriter(Channels.newChannel(optionalOutput), "UTF-8");
  JsonWriter optionalOutputWriter = new JsonWriter(writer);
  optionalOutputWriter.setIndent("  ");
  new Gson().toJson(newData, optionalOutputWriter);
  optionalOutputWriter.flush();
}
项目:FaceDistinguish    文件:HttpUtil.java   
/**
 * 将流转换为字符串
 *
 * @param is
 * @return
 * @throws IOException
 */
public static String readStreamAsStr(InputStream is) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    WritableByteChannel dest = Channels.newChannel(bos);
    ReadableByteChannel src = Channels.newChannel(is);
    ByteBuffer bb = ByteBuffer.allocate(4096);

    while (src.read(bb) != -1) {
        bb.flip();
        dest.write(bb);
        bb.clear();
    }
    src.close();
    dest.close();

    return new String(bos.toByteArray(), Constants.ENCODING);
}
项目:i_stolbov    文件:CommandFactoryServer.java   
/**
 * execute.
 * @param cmd - cmd
 * @throws IOException - IOException
 */
@Override
public void execute(Command cmd) throws IOException {
    Path filePath = workPath.resolve(cmd.getParam()).normalize();
    if (Files.exists(filePath, LinkOption.NOFOLLOW_LINKS)
            && !Files.isDirectory(filePath) && Files.isReadable(filePath)) {
        dataOutputStream.writeUTF(SUCCESS);
        dataOutputStream.flush();

        WritableByteChannel wbc = Channels.newChannel(dataOutputStream);
        FileInputStream fis = new FileInputStream(filePath.toString());
        fis.getChannel().transferTo(0, Long.MAX_VALUE, wbc);
        wbc.close();
    } else {
        dataOutputStream.writeUTF(ERROR);
        dataOutputStream.flush();
    }
}
项目:i_stolbov    文件:CommandFactoryClient.java   
/**
 * execute.
 * @param cmd - cmd
 * @throws IOException - IOException
 */
@Override
public void execute(Command cmd) throws IOException {
    Path filePath = Paths.get(cmd.getParam());
    if (Files.exists(filePath, LinkOption.NOFOLLOW_LINKS)
            && !Files.isDirectory(filePath) && Files.isReadable(filePath)) {

        System.out.println("Uploading...");

        ObjectOutputStream oos = new ObjectOutputStream(outputStream);
        oos.writeObject(cmd);
        oos.flush();

        WritableByteChannel rbc = Channels.newChannel(new DataOutputStream(outputStream));
        FileInputStream fis = new FileInputStream(cmd.getParam());
        fis.getChannel().transferTo(0, Long.MAX_VALUE, rbc);
        rbc.close();

        System.out.println("Done.");
    } else {
        System.out.println("Error. Please try again.");
    }
}
项目:hype    文件:StagingUtil.java   
/**
 * Copies the contents of the classpathElement to the output channel.
 *
 * <p>If the classpathElement is a directory, a Zip stream is constructed on the fly,
 * otherwise the file contents are copied as-is.
 *
 * <p>The output channel is not closed.
 */
private static void copyContent(String classpathElement, WritableByteChannel outputChannel)
    throws IOException {
  final File classpathElementFile = new File(classpathElement);
  if (classpathElementFile.isDirectory()) {
    ZipFiles.zipDirectory(classpathElementFile, Channels.newOutputStream(outputChannel));
  } else {
    Files.asByteSource(classpathElementFile).copyTo(Channels.newOutputStream(outputChannel));
  }
}
项目:sstable-adaptor    文件:CompressedSequentialWriter.java   
/**
 * Create CompressedSequentialWriter without digest file.
 *
 * @param file File to write
 * @param offsetsPath File name to write compression metadata
 * @param digestFile File to write digest
 * @param option Write option (buffer size and type will be set the same as compression params)
 * @param parameters Compression mparameters
 * @param sstableMetadataCollector Metadata collector
 */
public CompressedSequentialWriter(String file,
                                  String offsetsPath,
                                  String digestFile,
                                  SequentialWriterOption option,
                                  CompressionParams parameters,
                                  MetadataCollector sstableMetadataCollector,
                                  Configuration conf)
{
    super(file,
            SequentialWriterOption.newBuilder()
                        .bufferSize(option.bufferSize())
                        .bufferType(option.bufferType())
                        .bufferSize(parameters.chunkLength())
                        .bufferType(parameters.getSstableCompressor().preferredBufferType())
                        .finishOnClose(option.finishOnClose())
                        .build(),
            conf);
    this.compressor = parameters.getSstableCompressor();
    this.digestFile = Optional.ofNullable(digestFile);

    // buffer for compression should be the same size as buffer itself
    compressed = compressor.preferredBufferType().allocate(compressor.initialCompressedBufferLength(buffer.capacity()));

    /* Index File (-CompressionInfo.db component) and it's header */
    metadataWriter = CompressionMetadata.Writer.open(parameters, offsetsPath, conf);

    this.sstableMetadataCollector = sstableMetadataCollector;
    crcMetadata = new ChecksumWriter(new DataOutputStream(Channels.newOutputStream(channel)), conf);
}
项目:CentauriCloud    文件:LibraryDownloader.java   
@SneakyThrows
public void downloadLib(String url, String libDir, String outputName) {
    Cloud.getLogger().info("Download {}...", outputName);
    URL website = new URL(url);
    ReadableByteChannel rbc = Channels.newChannel(website.openStream());
    FileOutputStream fos = new FileOutputStream(libDir + outputName);
    fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
    Cloud.getLogger().info("Finished downloading {}!", outputName);
}
项目:incubator-netbeans    文件:JShellConnection.java   
synchronized boolean acceptSocketAndKey(int key, SocketChannel socket, ObjectInputStream istm) throws IOException {
    if (closed) {
        return false;
    }
    if (id != key) {
        return false;
    }
    this.ostm = Channels.newOutputStream(socket);
    this.istm = istm;
    this.controlSocket = socket;
    notify();
    return true;
}
项目:openarch    文件:Native.java   
public void addLibrary(String name) throws Exception {
    OpenArch.log.info(String.format("Loading %s.", name));

    String libPath = String.format("/assets/%s/lib/%s", OpenArch.MODID, name);
    URL libUrl = getClass().getResource(libPath);
    ReadableByteChannel in = Channels.newChannel(libUrl.openStream());

    String tmpLibPath = String.format("%s/%s", tmpDir, name);
    File tmpLibFile = new File(tmpLibPath);

    if (tmpLibFile.exists()) {
        return;
    }

    FileChannel out = new FileOutputStream(tmpLibFile).getChannel();

    out.transferFrom(in, 0, Long.MAX_VALUE);

    tmpLibFile.deleteOnExit();

    if (!tmpLibFile.setReadable(true, false)) {
        throw new Exception("Failed to set readable flag on the library");
    }

    if (!tmpLibFile.setWritable(true, false)) {
        throw new Exception("Failed to set writable flag on the library");
    }

    if (!tmpLibFile.setExecutable(true, false)) {
        throw new Exception("Failed to set executable flag on the library");
    }

    out.close();
    in.close();
}
项目:ranch2git    文件:FileAgent.java   
public static long downloadFromWebResource(String webURL, String destinationPath, String authUser, String authPass) throws IOException {
    if(authUser != null && authPass != null){
        Authenticator.setDefault (new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(authUser,authPass.toCharArray());}
        });
    }

    URL website = new URL(webURL);
    ReadableByteChannel rbc = Channels.newChannel(website.openStream());
    FileOutputStream fos = new FileOutputStream(destinationPath);
    fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
    return new File(destinationPath).length();
}
项目:alfresco-object-storage-connectors    文件:OpenIOContentReader.java   
@Override
protected ReadableByteChannel getDirectReadableChannel() {
    if (!exists()) {
        throw new ContentIOException("Content object does not exist on OpenIO");
    }

    try {
        final ObjectInfo fileObjectMetadata = client.getObjectInfo(this.oioUrl);
        return Channels.newChannel(this.client.downloadObject(fileObjectMetadata));
    } catch (Exception e) {
        throw new ContentIOException("Unable to retrieve content object from OpenIO", e);
    }

}
项目:hadoop-oss    文件:Server.java   
/**
 * Process a wrapped RPC Request - unwrap the SASL packet and process
 * each embedded RPC request 
 * @param inBuf - SASL wrapped request of one or more RPCs
 * @throws IOException - SASL packet cannot be unwrapped
 * @throws WrappedRpcServerException - an exception that has already been 
 *         sent back to the client that does not require verbose logging
 *         by the Listener thread
 * @throws InterruptedException
 */    
private void unwrapPacketAndProcessRpcs(byte[] inBuf)
    throws WrappedRpcServerException, IOException, InterruptedException {
  if (LOG.isDebugEnabled()) {
    LOG.debug("Have read input token of size " + inBuf.length
        + " for processing by saslServer.unwrap()");
  }
  inBuf = saslServer.unwrap(inBuf, 0, inBuf.length);
  ReadableByteChannel ch = Channels.newChannel(new ByteArrayInputStream(
      inBuf));
  // Read all RPCs contained in the inBuf, even partial ones
  while (true) {
    int count = -1;
    if (unwrappedDataLengthBuffer.remaining() > 0) {
      count = channelRead(ch, unwrappedDataLengthBuffer);
      if (count <= 0 || unwrappedDataLengthBuffer.remaining() > 0)
        return;
    }

    if (unwrappedData == null) {
      unwrappedDataLengthBuffer.flip();
      int unwrappedDataLength = unwrappedDataLengthBuffer.getInt();
      unwrappedData = ByteBuffer.allocate(unwrappedDataLength);
    }

    count = channelRead(ch, unwrappedData);
    if (count <= 0 || unwrappedData.remaining() > 0)
      return;

    if (unwrappedData.remaining() == 0) {
      unwrappedDataLengthBuffer.clear();
      unwrappedData.flip();
      processOneRpc(unwrappedData.array());
      unwrappedData = null;
    }
  }
}
项目:jmeter-bzm-plugins    文件:RandomBufferedReader.java   
public RandomBufferedReader(Reader in, RandomAccessFile raf, String encoding) throws UnsupportedEncodingException {
    super(in);
    this.raf = raf;
    this.encoding = encoding;
    this.is = Channels.newInputStream(raf.getChannel());
    initBufferedReader();
}
项目:Parabot-317-API-Minified-OS-Scape    文件:NetUtil.java   
public static boolean downloadFile(String url, String location) {
    try {

        final URLConnection connection = createURLConnection(url);

        final int  contentLength = connection.getContentLength();
        final File destination   = new File(location);

        if (destination.exists()) {
            final URLConnection savedFileConnection = destination.toURI().toURL().openConnection();
            if (savedFileConnection.getContentLength() == contentLength) {
                return true;
            }
        } else {
            final File parent = destination.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }
        }

        final ReadableByteChannel rbc = Channels.newChannel(connection.getInputStream());

        final FileOutputStream fos = new FileOutputStream(destination);
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        fos.close();

    } catch (IOException exception) {
        exception.printStackTrace();
        return false;
    }

    System.out.println(url + "->" + location);
    return new File(location).exists();
}
项目:aos-FileCoreLibrary    文件:LocalStorageFileEditor.java   
@Override
public InputStream getInputStream(long from) throws Exception {
    RandomAccessFile raf = new RandomAccessFile(new File(mUri.getPath()), "r");
    if (raf != null) {
        raf.seek(from);
        return Channels.newInputStream(raf.getChannel());
    }
    return null;
}
项目:AutoUpdaterAPI    文件:UtilDownloader.java   
public static void downloadFile(String url, String location) throws IOException {
    URL website = new URL(url);
    ReadableByteChannel rbc = Channels.newChannel(website.openStream());
    File yourFile = new File(location);
    yourFile.getParentFile().mkdirs();
    if (!yourFile.exists()) {
        yourFile.createNewFile();
    }
    FileOutputStream fos = new FileOutputStream(yourFile);
    fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
    fos.close();
}
项目:ranch2git    文件:FileAgent.java   
public static long downloadFromWebResource(String webURL, String destinationPath) throws IOException {
    URL website = new URL(webURL);
    ReadableByteChannel rbc = Channels.newChannel(website.openStream());
    FileOutputStream fos = new FileOutputStream(destinationPath);
    fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
    rbc.close();
    fos.close();
    return new File(destinationPath).length();
}
项目:rest-client    文件:TestUtils.java   
public static InputStream mockStream(long length) {
    try {
        RandomAccessFile raf = new RandomAccessFile("t", "rw");
        raf.setLength(length);

        return Channels.newInputStream(raf.getChannel());
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
项目:cornerstone    文件:IOUtils.java   
public static byte[] reverseRead(final Path path,Charset charset,long size) throws IOException {
    try (SeekableByteChannel sbc = Files.newByteChannel(path);
         InputStream in = Channels.newInputStream(sbc)) {
        long startIndex = sbc.size() - size;
        if (startIndex < 0) {
            startIndex = 0;
        }
        in.skip(startIndex);
        if (size > (long) MAX_BUFFER_SIZE)
            throw new OutOfMemoryError("Required array size too large");

        return read(in, (int) size);

    }
}
项目:Slimefun4-Chinese-Version    文件:GitHubConnector.java   
public void pullFile()
{
    if(SlimefunStartup.getCfg().getBoolean("options.print-out-github-data-retrieving"))
        System.out.println((new StringBuilder("[Slimefun - GitHub] 正从 Github 上获取 '")).append(getFileName()).append(".json' ...").toString());
    try
    {
        URL website = new URL((new StringBuilder("https://api.github.com/repos/")).append(getRepository()).append(getURLSuffix()).toString());
        URLConnection connection = website.openConnection();
        connection.setConnectTimeout(3000);
        connection.addRequestProperty("User-Agent", "Slimefun 4 GitHub Agent (by TheBusyBiscuit)");
        connection.setDoOutput(true);
        java.nio.channels.ReadableByteChannel rbc = Channels.newChannel(connection.getInputStream());
        FileOutputStream fos = new FileOutputStream(file);
        fos.getChannel().transferFrom(rbc, 0L, 0x7fffffffffffffffL);
        fos.close();
        parseData();
    }
    catch(IOException e)
    {
        if(SlimefunStartup.getCfg().getBoolean("options.print-out-github-data-retrieving"))
            System.err.println("[Slimefun - GitHub] 错误 - 无法连接至 GitHub!");
        if(hasData())
            parseData();
        else
            onFailure();
    }
}
项目:alfresco-repository    文件:TransferSummaryReportImpl.java   
protected Writer createUnderlyingLogWriter(String transferId)
{
    if (reportFile == null)
    {
        reportFile = createTransferRecord(transferId);
    }
    ContentWriter contentWriter = contentService.getWriter(reportFile, ContentModel.PROP_CONTENT, true);
    contentWriter.setMimetype(MimetypeMap.MIMETYPE_XML);
    contentWriter.setEncoding("UTF-8");
    return Channels.newWriter(contentWriter.getWritableChannel(), "UTF-8");
}
项目:alfresco-repository    文件:RepoTransferProgressMonitorImpl.java   
@Override
protected Writer createUnderlyingLogWriter(String transferId)
{
    NodeRef node = new NodeRef(transferId);
    ContentWriter contentWriter = contentService.getWriter(node, ContentModel.PROP_CONTENT, true);
    contentWriter.setMimetype(MimetypeMap.MIMETYPE_XML);
    contentWriter.setEncoding("UTF-8");
    return Channels.newWriter(contentWriter.getWritableChannel(), "UTF-8");
}