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


Java FileChannel.write方法代码示例

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


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

示例1: writeFileFromBytesByChannel

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * 将字节数组写入文件
 *
 * @param file    文件
 * @param bytes   字节数组
 * @param append  是否追加在文件末
 * @param isForce 是否写入文件
 * @return {@code true}: 写入成功<br>{@code false}: 写入失败
 */
public static boolean writeFileFromBytesByChannel(File file, final byte[] bytes, boolean append, boolean isForce) {
    if (bytes == null) return false;
    if (!append && !FileUtils.createFileByDeleteOldFile(file)) return false;
    FileChannel fc = null;
    try {
        fc = new RandomAccessFile(file, "rw").getChannel();
        fc.position(fc.size());
        fc.write(ByteBuffer.wrap(bytes));
        if (isForce) fc.force(true);
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        CloseUtils.closeIO(fc);
    }
}
 
开发者ID:hoangkien0705,项目名称:Android-UtilCode,代码行数:27,代码来源:FileIOUtils.java

示例2: analyzeAndTagFile

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
private static void analyzeAndTagFile(String inputFilename) throws Exception {
	File file = new File(inputFilename);
	String outFilename = config.getString("output.dirpath") + file.getName() + config.getString("output.postfix");
	RandomAccessFile outStream = new RandomAccessFile(outFilename, "rw");
	FileChannel outChannel = outStream.getChannel();
	LineIterator it = FileUtils.lineIterator(file, config.getString("input.charset"));


	try {
		while (it.hasNext()) {
			String line = it.nextLine().trim();

			if (!"".equals(line)) {
				outChannel.write(Charset.forName(config.getString("output.charset")).newEncoder().encode(CharBuffer.wrap(tagger.tag(komoran.analyze(line)) + config.getString("delimiter.line"))));
			}
		}
	}
	finally {
		LineIterator.closeQuietly(it);
		outStream.close();
		outChannel.close();
	}
}
 
开发者ID:9bow,项目名称:KOMORANPoSTagger,代码行数:24,代码来源:Application.java

示例3: rewriteRiffHeaderSize

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * Rewrite RAF header to reflect new file length
 *
 * @param fc
 * @throws IOException
 */
private void rewriteRiffHeaderSize(FileChannel fc) throws IOException {

    fc.position(IffHeaderChunk.SIGNATURE_LENGTH);
    ByteBuffer bb = ByteBuffer.allocateDirect(IffHeaderChunk.SIZE_LENGTH);
    bb.order(ByteOrder.BIG_ENDIAN);
    int size = ((int) fc.size()) - SIGNATURE_LENGTH - SIZE_LENGTH;
    bb.putInt(size);
    bb.flip();
    fc.write(bb);
}
 
开发者ID:GlennioTech,项目名称:MetadataEditor,代码行数:17,代码来源:AiffTagWriter.java

示例4: corruptTranslogs

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * Randomly overwrite some bytes in the translog files
 */
private void corruptTranslogs(Path directory) throws Exception {
    Path[] files = FileSystemUtils.files(directory, "translog-*");
    for (Path file : files) {
        logger.info("--> corrupting {}...", file);
        FileChannel f = FileChannel.open(file, StandardOpenOption.READ, StandardOpenOption.WRITE);
        int corruptions = scaledRandomIntBetween(10, 50);
        for (int i = 0; i < corruptions; i++) {
            // note: with the current logic, this will sometimes be a no-op
            long pos = randomIntBetween(0, (int) f.size());
            ByteBuffer junk = ByteBuffer.wrap(new byte[]{randomByte()});
            f.write(junk, pos);
        }
        f.close();
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:19,代码来源:TranslogTests.java

示例5: writeFileFromBytesByChannel

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * 将字节数组写入文件
 *
 * @param file    文件
 * @param bytes   字节数组
 * @param append  是否追加在文件末
 * @param isForce 是否写入文件
 * @return {@code true}: 写入成功<br>{@code false}: 写入失败
 */
public static boolean writeFileFromBytesByChannel(File file, final byte[] bytes, boolean append, boolean isForce) {
    if (bytes == null) return false;
    FileChannel fc = null;
    try {
        fc = new FileOutputStream(file, append).getChannel();
        fc.position(fc.size());
        fc.write(ByteBuffer.wrap(bytes));
        if (isForce) fc.force(true);
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        CloseUtils.closeIO(fc);
    }
}
 
开发者ID:pan2yong22,项目名称:AndroidUtilCode-master,代码行数:26,代码来源:FileIOUtils.java

示例6: writeFileFromBytesByChannel

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * 将字节数组写入文件
 *
 * @param file    文件
 * @param bytes   字节数组
 * @param append  是否追加在文件末
 * @param isForce 是否写入文件
 * @return {@code true}: 写入成功<br>{@code false}: 写入失败
 */
public static boolean writeFileFromBytesByChannel(final File file, final byte[] bytes, final boolean append, final boolean isForce) {
    if (bytes == null) return false;
    FileChannel fc = null;
    try {
        fc = new FileOutputStream(file, append).getChannel();
        fc.position(fc.size());
        fc.write(ByteBuffer.wrap(bytes));
        if (isForce) fc.force(true);
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        CloseUtils.closeIO(fc);
    }
}
 
开发者ID:Wilshion,项目名称:HeadlineNews,代码行数:26,代码来源:FileIOUtils.java

示例7: create

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * Initialize a new file, write the empty structure to disk and return a new
 * accessor to it
 * 
 * @param file
 *            The file to create. This file must not exists.
 * @param startDate
 *            the start date of the file
 * @param endDate
 *            the end date of the file
 * @return a newly created file accessor
 * @throws Exception
 *             if anything goes wrong
 */
public static DataFileAccessorImpl create ( final File file, final Date startDate, final Date endDate ) throws Exception
{
    logger.debug ( "Creating new file: {}", file );

    if ( !file.createNewFile () )
    {
        throw new IllegalStateException ( String.format ( "Unable to create file %s, already exists", file ) );
    }

    final FileOutputStream out = new FileOutputStream ( file );

    try
    {
        final FileChannel channel = out.getChannel ();

        final ByteBuffer buffer = ByteBuffer.allocate ( 100 );
        buffer.putInt ( 0x1202 ); // magic marker
        buffer.putInt ( 0x0101 ); // version
        buffer.putLong ( startDate.getTime () ); // start timestamp
        buffer.putLong ( endDate.getTime () ); // end timestamp

        buffer.flip ();

        while ( buffer.hasRemaining () )
        {
            final int rc = channel.write ( buffer );
            logger.debug ( "Header written - {} bytes", rc );
        }

        return new DataFileAccessorImpl ( file );
    }
    finally
    {
        out.close ();
    }
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:51,代码来源:DataFileAccessorImpl.java

示例8: writeFileFromBytes

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
private static void writeFileFromBytes(File file, byte[] bytes) {
    FileChannel fc = null;
    try {
        fc = new FileOutputStream(file, false).getChannel();
        fc.write(ByteBuffer.wrap(bytes));
        fc.force(true);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        CloseUtils.closeIO(fc);
    }
}
 
开发者ID:pan2yong22,项目名称:AndroidUtilCode-master,代码行数:13,代码来源:CacheUtils.java

示例9: transferTo

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
@Override
public long transferTo(long position, long count, FileChannel target) throws IOException {
    if (anyAreSet(state, STATE_DONE)) {
        return -1;
    }
    beforeRead();
    if (waitingForFrame) {
        return 0;
    }
    try {
        if (frameDataRemaining == 0 && anyAreSet(state, STATE_LAST_FRAME)) {
            return -1;
        } else if (data != null) {
            int old = data.getResource().limit();
            try {
                if (count < data.getResource().remaining()) {
                    data.getResource().limit((int) (data.getResource().position() + count));
                }
                int written = target.write(data.getResource(), position);
                frameDataRemaining -= written;
                return written;
            } finally {
                data.getResource().limit(old);
            }
        }
        return 0;
    } finally {
        exitRead();
    }
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:31,代码来源:AbstractFramedStreamSourceChannel.java

示例10: xferTest03

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
@Test
public void xferTest03() throws Exception { // for bug 4559072
    byte[] srcData = new byte[] {1,2,3,4} ;

    // get filechannel for the source file.
    File source = File.createTempFile("source", null);
    source.deleteOnExit();
    RandomAccessFile raf1 = new RandomAccessFile(source, "rw");
    FileChannel fc1 = raf1.getChannel();
    fc1.truncate(0);

    // write out data to the file channel
    int bytesWritten = 0;
    while (bytesWritten < 4) {
        bytesWritten = fc1.write(ByteBuffer.wrap(srcData));
    }

    // get filechannel for the dst file.
    File dest = File.createTempFile("dest", null);
    dest.deleteOnExit();
    RandomAccessFile raf2 = new RandomAccessFile(dest, "rw");
    FileChannel fc2 = raf2.getChannel();
    fc2.truncate(0);

    fc1.transferTo(0, srcData.length + 1, fc2);

    if (fc2.size() > 4)
        throw new Exception("xferTest03 failed");

    fc1.close();
    fc2.close();
    raf1.close();
    raf2.close();

    source.delete();
    dest.delete();
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:38,代码来源:Transfer.java

示例11: write

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
static void write(FileChannel fc, int b) throws IOException {
    ByteBuffer buf = ByteBuffer.allocate(1);
    buf.put((byte)b);
    buf.flip();
    if (rand.nextBoolean()) {
        ByteBuffer[] bufs = new ByteBuffer[1];
        bufs[0] = buf;
        fc.write(bufs);
    } else {
        fc.write(buf);
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:13,代码来源:AtomicAppend.java

示例12: writeToFile

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * Writes data to a file.
 *
 * @param data
 * @throws IOException
 */
protected void writeToFile(List<ExportEntry> data) throws IOException {
    FileChannel fc = fileOutpuStream.getChannel();
    byte[] lineFeed = "\n".getBytes(Charset.forName("UTF-8"));

    for (ExportEntry entry : data) {
        byte[] messageBytes = entry.toByteEntryLine();
        fc.write(ByteBuffer.wrap(messageBytes));
        fc.write(ByteBuffer.wrap(lineFeed));
    }

    fc.close();
}
 
开发者ID:tiweGH,项目名称:OpenDiabetes,代码行数:19,代码来源:FileExporter.java

示例13: writeBuffer

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * Write the data in the ByteBuffer, and eventually on disk if needed.
 *
 * @param channel The channel we want to write to
 * @param bb The ByteBuffer we want to feed
 * @param buffer The data to inject
 * @throws IOException If the write failed
 */
private void writeBuffer( FileChannel channel, ByteBuffer bb, byte[] buffer ) throws IOException
{
    int size = buffer.length;
    int pos = 0;

    // Loop until we have written all the data
    do
    {
        if ( bb.remaining() >= size )
        {
            // No flush, as the ByteBuffer is big enough
            bb.put( buffer, pos, size );
            size = 0;
        }
        else
        {
            // Flush the data on disk, reinitialize the ByteBuffer
            int len = bb.remaining();
            size -= len;
            bb.put( buffer, pos, len );
            pos += len;

            bb.flip();

            channel.write( bb );

            bb.clear();
        }
    }
    while ( size > 0 );
}
 
开发者ID:apache,项目名称:directory-mavibot,代码行数:40,代码来源:PersistedBTree.java

示例14: xferTest05

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
@Test
public void xferTest05() throws Exception { // for bug 4638365
    // Create a source file & large sink file for the test
    File source = File.createTempFile("blech", null);
    source.deleteOnExit();
    initTestFile(source, 100);

    // Create the sink file as a sparse file if possible
    File sink = null;
    FileChannel fc = null;
    while (fc == null) {
        sink = File.createTempFile("sink", null);
        // re-create as a sparse file
        sink.delete();
        try {
            fc = FileChannel.open(sink.toPath(),
                                  StandardOpenOption.CREATE_NEW,
                                  StandardOpenOption.WRITE,
                                  StandardOpenOption.SPARSE);
        } catch (FileAlreadyExistsException ignore) {
            // someone else got it
        }
    }
    sink.deleteOnExit();

    long testSize = ((long)Integer.MAX_VALUE) * 2;
    try {
        out.println("  Writing large file...");
        long t0 = System.nanoTime();
        fc.write(ByteBuffer.wrap("Use the source!".getBytes()),
                 testSize - 40);
        long t1 = System.nanoTime();
        out.printf("  Wrote large file in %d ns (%d ms) %n",
        t1 - t0, TimeUnit.NANOSECONDS.toMillis(t1 - t0));
    } catch (IOException e) {
        // Can't set up the test, abort it
        err.println("xferTest05 was aborted.");
        return;
    } finally {
        fc.close();
    }

    // Get new channels for the source and sink and attempt transfer
    FileChannel sourceChannel = new FileInputStream(source).getChannel();
    try {
        FileChannel sinkChannel = new RandomAccessFile(sink, "rw").getChannel();
        try {
            long bytesWritten = sinkChannel.transferFrom(sourceChannel,
                                                         testSize - 40, 10);
            if (bytesWritten != 10) {
                throw new RuntimeException("Transfer test 5 failed " +
                                           bytesWritten);
            }
        } finally {
            sinkChannel.close();
        }
    } finally {
        sourceChannel.close();
    }

    source.delete();
    sink.delete();
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:64,代码来源:Transfer4GBFile.java

示例15: writeBufferToFile

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * Write the data from the buffer to the file
 *
 * @param file
 * @param headerBuffer
 * @param bodyByteBuffer
 * @param padding
 * @param sizeIncPadding
 * @param audioStartLocation
 * @throws IOException
 */
protected void writeBufferToFile(File file, ByteBuffer headerBuffer, byte[] bodyByteBuffer, int padding, int sizeIncPadding, long audioStartLocation) throws IOException
{
    FileChannel fc = null;
    FileLock fileLock = null;

    //We need to adjust location of audio file if true
    if (sizeIncPadding > audioStartLocation)
    {
        logger.finest("Adjusting Padding");
        adjustPadding(file, sizeIncPadding, audioStartLocation);
    }

    try
    {
        fc = new RandomAccessFile(file, "rw").getChannel();
        fileLock = getFileLockForWriting(fc, file.getPath());
        fc.write(headerBuffer);
        fc.write(ByteBuffer.wrap(bodyByteBuffer));
        fc.write(ByteBuffer.wrap(new byte[padding]));
    }
    catch (FileNotFoundException fe)
    {
        logger.log(Level.SEVERE, getLoggingFilename() + fe.getMessage(), fe);
        if (fe.getMessage().contains(FileSystemMessage.ACCESS_IS_DENIED.getMsg()) || fe.getMessage().contains(FileSystemMessage.PERMISSION_DENIED.getMsg()))
        {
            logger.severe(ErrorMessage.GENERAL_WRITE_FAILED_TO_OPEN_FILE_FOR_EDITING.getMsg(file.getPath()));
            throw new UnableToModifyFileException(ErrorMessage.GENERAL_WRITE_FAILED_TO_OPEN_FILE_FOR_EDITING.getMsg(file.getPath()));
        }
        else
        {
            logger.severe(ErrorMessage.GENERAL_WRITE_FAILED_TO_OPEN_FILE_FOR_EDITING.getMsg(file.getPath()));
            throw new UnableToCreateFileException(ErrorMessage.GENERAL_WRITE_FAILED_TO_OPEN_FILE_FOR_EDITING.getMsg(file.getPath()));
        }
    }
    catch (IOException ioe)
    {
        logger.log(Level.SEVERE, getLoggingFilename() + ioe.getMessage(), ioe);
        if (ioe.getMessage().equals(FileSystemMessage.ACCESS_IS_DENIED.getMsg()))
        {
            logger.severe(ErrorMessage.GENERAL_WRITE_FAILED_TO_OPEN_FILE_FOR_EDITING.getMsg(file.getParentFile().getPath()));
            throw new UnableToModifyFileException(ErrorMessage.GENERAL_WRITE_FAILED_TO_OPEN_FILE_FOR_EDITING.getMsg(file.getParentFile().getPath()));
        }
        else
        {
            logger.severe(ErrorMessage.GENERAL_WRITE_FAILED_TO_OPEN_FILE_FOR_EDITING.getMsg(file.getParentFile().getPath()));
            throw new UnableToCreateFileException(ErrorMessage.GENERAL_WRITE_FAILED_TO_OPEN_FILE_FOR_EDITING.getMsg(file.getParentFile().getPath()));
        }
    }
    finally
    {
        if (fc != null)
        {
            if (fileLock != null)
            {
                fileLock.release();
            }
            fc.close();
        }
    }
}
 
开发者ID:GlennioTech,项目名称:MetadataEditor,代码行数:72,代码来源:AbstractID3v2Tag.java


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