当前位置: 首页>>代码示例>>Java>>正文


Java Channels类代码示例

本文整理汇总了Java中java.nio.channels.Channels的典型用法代码示例。如果您正苦于以下问题:Java Channels类的具体用法?Java Channels怎么用?Java Channels使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Channels类属于java.nio.channels包,在下文中一共展示了Channels类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: load

import java.nio.channels.Channels; //导入依赖的package包/类
@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;
}
 
开发者ID:curioswitch,项目名称:curiostack,代码行数:21,代码来源:CloudStorageBuildCacheService.java

示例2: readBytes

import java.nio.channels.Channels; //导入依赖的package包/类
/**
 * 
 */
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;
}
 
开发者ID:annoflex,项目名称:annoflex,代码行数:26,代码来源:SystemToolkit.java

示例3: parse

import java.nio.channels.Channels; //导入依赖的package包/类
@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;
}
 
开发者ID:arodchen,项目名称:MaxSim,代码行数:20,代码来源:Parser.java

示例4: partitionRead

import java.nio.channels.Channels; //导入依赖的package包/类
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);

        }
    }
 
开发者ID:ctripcorp,项目名称:cornerstone,代码行数:17,代码来源:IOUtils.java

示例5: getContentOutputStream

import java.nio.channels.Channels; //导入依赖的package包/类
/**
 * @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);
    }
}
 
开发者ID:Alfresco,项目名称:alfresco-repository,代码行数:20,代码来源:AbstractContentWriter.java

示例6: update

import java.nio.channels.Channels; //导入依赖的package包/类
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;
    }
}
 
开发者ID:Ptrk25,项目名称:CDN-FX-2.2,代码行数:20,代码来源:Updater.java

示例7: parseDatHeader

import java.nio.channels.Channels; //导入依赖的package包/类
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;
    }
}
 
开发者ID:nla,项目名称:httrack2warc,代码行数:27,代码来源:NdxCache.java

示例8: startRead

import java.nio.channels.Channels; //导入依赖的package包/类
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);
                }
            }));
        }
    }));
}
 
开发者ID:lizhangqu,项目名称:chromium-net-for-android,代码行数:21,代码来源:JavaUrlRequest.java

示例9: load

import java.nio.channels.Channels; //导入依赖的package包/类
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"));
	}
 
开发者ID:Njol,项目名称:Motunautr,代码行数:18,代码来源:Settings.java

示例10: update

import java.nio.channels.Channels; //导入依赖的package包/类
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;
    }
}
 
开发者ID:Ptrk25,项目名称:CDN-FX-2.2,代码行数:21,代码来源:XMLUpdater.java

示例11: testNotEnoughSpace

import java.nio.channels.Channels; //导入依赖的package包/类
@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);
}
 
开发者ID:Genymobile,项目名称:gnirehtet,代码行数:21,代码来源:StreamBufferTest.java

示例12: setAttributes

import java.nio.channels.Channels; //导入依赖的package包/类
@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());
	}
}
 
开发者ID:saalfeldlab,项目名称:n5,代码行数:17,代码来源:N5FSWriter.java

示例13: transfer

import java.nio.channels.Channels; //导入依赖的package包/类
/**
 * 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;
    }
}
 
开发者ID:openmicroscopy,项目名称:omero-ms-queue,代码行数:28,代码来源:FileOps.java

示例14: ioResourceToByteBuffer

import java.nio.channels.Channels; //导入依赖的package包/类
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;
}
 
开发者ID:tek256,项目名称:LD38,代码行数:27,代码来源:Util.java

示例15: getPreview

import java.nio.channels.Channels; //导入依赖的package包/类
/**
 * 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);
}
 
开发者ID:xm-online,项目名称:xm-lep,代码行数:29,代码来源:StringUtils.java


注:本文中的java.nio.channels.Channels类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。