用java.nio使用mmap将一个字符串写入文件

@Test 
public void test_nio_write_string(){ 
    String s= new String("你好"); 
    File file=new File("/tmp/test.txt"); 
    RandomAccessFile outputFile = null; 
    try{ 
        outputFile=new RandomAccessFile(file,"rw"); 
    } catch(FileNotFoundException e) { 
        logger.error("创建文件失败",e); 
        Assert.fail(); 
    } 
    FileChannel outChannel=outputFile.getChannel(); 

    try{ 
        MappedByteBuffer buffer; 
        byte[] data=s.getBytes(); 
        buffer=outChannel.map(FileChannel.MapMode.READ_WRITE, 0,data.length); 
        buffer.put(data,0,data.length); 
        buffer.force(); 
        outChannel.close(); 
        outputFile.close(); 
    }catch(IOException ex){ 
        logger.error("io错误",ex); 
        Assert.fail(); 
    } 
}

此博客中的热门博文

少写代码,多读别人写的代码

在windows下使用llvm+clang

tensorflow distributed runtime初窥