nio 备份

package test.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Date;



/** *//**
 * @author lichun
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class FileUtil{
    
    public static ByteBuffer readFile(String filename) throws Exception{
        FileChannel fiChannel = new FileInputStream(filename).getChannel();
        MappedByteBuffer mBuf;
        mBuf = fiChannel.map(FileChannel.MapMode.READ_ONLY, 0, fiChannel.size());
        fiChannel.close();
        fiChannel = null;
        
        return mBuf;      
        
    }
    
    
    public static void saveFile(ByteBuffer src, String filename) throws Exception{
        FileChannel foChannel = new FileOutputStream(filename).getChannel();
        foChannel.write(src);
        foChannel.close();  
        foChannel = null; 
    }
    
    public static void saveFile(FileChannel fiChannel, String filename) throws IOException{
        MappedByteBuffer mBuf;
        mBuf = fiChannel.map(FileChannel.MapMode.READ_ONLY, 0, fiChannel.size());

        FileChannel foChannel = new FileOutputStream(filename).getChannel();
        foChannel.write(mBuf);
        
        fiChannel.close();
        foChannel.close(); 
        
        fiChannel = null;
        foChannel = null; 
    }
    
    public static void copyFile(String in,String out) throws IOException{
        FileChannel fin=new FileInputStream(in).getChannel();
        FileChannel fout=new FileOutputStream(out).getChannel();
        fout.transferFrom(fin,0,fin.size());
    }
    public static long forChannel(String f1,String f2) throws Exception{
        long time=new Date().getTime();
        int length=3097152;
        FileInputStream in=new FileInputStream(f1);
        FileOutputStream out=new FileOutputStream(f2);
        FileChannel inC=in.getChannel();
        FileChannel outC=out.getChannel();
        ByteBuffer b=null;
        while(true){
            if(inC.position()==inC.size()){
                inC.close();
                outC.close();
                return new Date().getTime()-time;
            }
            if((inC.size()-inC.position())<length){
                length=(int)(inC.size()-inC.position());
            }else
                length=2097152;
            b=ByteBuffer.allocateDirect(length);
            inC.read(b);
            b.flip();
            outC.write(b);
            outC.force(false);
        }
    }
    public static void main(String[] args) throws Exception {    
    	util.MyTools_common.startTimeDesc();
        final String from = "E:\\maying\\test\\HouseStructure.img";
        final String to = "E:\\xx.img";
//        ByteBuffer byteBuffer = FileUtil.readFile(from);
//        FileUtil.saveFile(byteBuffer, to);
//        byteBuffer = null;
        FileUtil.copyFile(from, to);
//        FileUtil.forChannel(from, to);
        util.MyTools_common.endTimeDesc();
        util.MyTools_common.useTimeDesc();
        
    }
}

 

package test.nio;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.*;


/** *//**
 * @author lichun
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class TransferFile{
    
    private String srcFile;
    
    List files = new ArrayList();
    ByteBuffer byteBuffer;
   
    public TransferFile(){
        createFileNames();
    }
    
    private void createFileNames(){
        for (int i = 0; i < 10; i++){
            files.add(i + "");
        }
    }  
    
    public List getFiles(){
        return this.files;
    }

    public String getSrcFile() {
        return srcFile;
    }

    public void setSrcFile(String srcFile){
        this.srcFile = srcFile;
    }
    
    public void saveFiles() throws FileNotFoundException{
        String tempFile;
        for (int i = 0; i < this.files.size(); i++) {
            tempFile = "test-files/" + (String)files.get(i) + ".txt";
            System.out.println("begin create thread for " + tempFile);
            
            FileChannel fiChannel = new FileInputStream(this.srcFile).getChannel();
            
            WriteFileThread writeFileThread = new WriteFileThread("writeFile", fiChannel, tempFile);
            writeFileThread.start();   
        }
        
    }

    public static void main(String[] args) throws Exception {
        final String srcFile = "test-files/transferFile.txt";
        TransferFile transferFile = new TransferFile();
        transferFile.setSrcFile(srcFile);
        transferFile.saveFiles();        
    }
}

 

 

package test.nio;

import java.io.IOException;
import java.nio.channels.FileChannel;

/** *//**
 * @author lichun
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class WriteFileThread extends Thread{

    private FileChannel fiChannel;
    private String fileName;
   
    public WriteFileThread(String name){
        super(name);
    }
    
    public WriteFileThread(String name, FileChannel fiChannel, String fileName){
        this(name);
        this.fiChannel = fiChannel;
        this.fileName = fileName;
    }
    
    public void setFiChannel(FileChannel fiChannel){
        this.fiChannel = fiChannel;
    }
    
    public FileChannel getFiChannel(){
    	return fiChannel;
    	
    }
    public void setFileName(String fileName){
    	this.fileName = fileName;
    }
    public String getFileName(){
    	return fileName;
    }
    public void run(){
    	System.out.println("in Thread: "+this.getName());
    	try {
			FileUtil.saveFile(this.fiChannel, this.fileName);
		} catch (IOException e) {
			System.out.println("The file is not founded: "+fileName);
			e.printStackTrace();
		}
		System.out.println("end Thread : "+ this.getName());
    }
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这是一个非常经典的 Java NIO 相关问题,Buffer 类是 Java NIO 系统中的一个核心类,它是一个抽象类,定义了许多抽象方法和一些常用的方法。在实际开发过程中,我们经常会使用到 Buffer 相关的 API,其中包括三个常用的函数:slice()、duplicate() 和 wrap()。 - slice():创建一个与原始缓冲区共享数据的新缓冲区,可以理解成是原始缓冲区的一个视图,二者共享数据。新缓冲区的容量是原始缓冲区的剩余元素数量,位置是原始缓冲区当前位置,限制是原始缓冲区的剩余元素数量,标记被忽略。这个方法的主要作用就是将原始缓冲区的一个子区域作为一个新的缓冲区来使用,这个新的缓冲区与原始缓冲区数据共享,所以对新缓冲区的操作也会对原始缓冲区产生影响。 示例代码: ``` ByteBuffer buffer = ByteBuffer.allocate(10); for (int i = 0; i < buffer.capacity(); i++) { buffer.put((byte) i); } buffer.position(2); buffer.limit(6); ByteBuffer sliceBuffer = buffer.slice(); for (int i = 0; i < sliceBuffer.capacity(); i++) { byte b = sliceBuffer.get(i); b *= 11; sliceBuffer.put(i, b); } buffer.position(0); buffer.limit(buffer.capacity()); while (buffer.hasRemaining()) { System.out.println(buffer.get()); } ``` 输出结果为: ``` 0 1 22 33 44 5 6 7 8 9 ``` - duplicate():创建一个原始缓冲区的副本,这个副本与原始缓冲区共享数据,但是它拥有自己的索引、标记、限制和容量等属性,对副本的修改不会影响到原始缓冲区。这个方法的主要作用就是复制一个原始缓冲区,用于多线程操作或者备份。 示例代码: ``` ByteBuffer buffer = ByteBuffer.allocate(10); for (int i = 0; i < buffer.capacity(); i++) { buffer.put((byte) i); } ByteBuffer duplicateBuffer = buffer.duplicate(); for (int i = 0; i < duplicateBuffer.capacity(); i++) { byte b = duplicateBuffer.get(i); b *= 11; duplicateBuffer.put(i, b); } buffer.position(0); buffer.limit(buffer.capacity()); while (buffer.hasRemaining()) { System.out.println(buffer.get()); } ``` 输出结果为: ``` 0 1 2 3 4 5 6 7 8 9 ``` - wrap():创建一个包装了给定数组的缓冲区,这个缓冲区的容量是给定数组的长度,位置为 0,限制为数组的长度,标记被忽略。这个方法的主要作用就是将一个数组包装成缓冲区,从而可以使用缓冲区提供的方法对数组进行操作。 示例代码: ``` byte[] bytes = new byte[10]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) i; } ByteBuffer buffer = ByteBuffer.wrap(bytes); for (int i = 0; i < buffer.capacity(); i++) { byte b = buffer.get(i); b *= 11; buffer.put(i, b); } for (byte b : bytes) { System.out.println(b); } ``` 输出结果为: ``` 0 11 22 33 44 55 66 77 88 99 ``` 以上就是 slice()、duplicate() 和 wrap() 函数的作用和区别,以及示例代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值