`

IO、文件、NIO 最佳阅读资料与实践

    博客分类:
  • Java
阅读更多
转载:IO、文件、NIO【草案一】
http://blog.csdn.net/silentbalanceyh/archive/2010/01/25/5252265.aspx

转载:IO、文件、NIO【草案二】
http://blog.csdn.net/silentbalanceyh/archive/2010/01/25/5252280.aspx

转载:IO、文件、NIO【草案三】
http://blog.csdn.net/silentbalanceyh/archive/2010/01/26/5252285.aspx

转载:IO、文件、NIO【草案四】
http://blog.csdn.net/silentbalanceyh/archive/2010/01/25/5252301.aspx

作者写得太详细了,太好了 以及相关的,一,二,三,是了解IO,NIO最好的参考资料,
为了方便面在不能上网的时候阅读,就下载了,见附件

实战代码(文件拷贝)

import java.io.File;
import java.io.FileInputStream;

import java.io.FileOutputStream;
import java.io.IOException;

import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class ReadWriteCompare {

	public static void main(String[] args) throws IOException {
		
		copyFileToNio("c:/dev.rar","c:/copy_dev.rar");
	}

	public static void copyFileToNio(String sourceFilePath, String newFilePath)
			throws IOException {
		  File file = new File(sourceFilePath);
		  if(!file.exists()){
			  System.err.println("要拷贝的源文件不存在,请重新指定文件路径.");
			  return;
		  }
		  createMkdirs(newFilePath);
		  copyFileToNio(file,newFilePath);
	}
	
	public static void createMkdirs(String filePath) throws IOException{
		int dirIndex = filePath.indexOf("/");
		int dirIndex2 = filePath.indexOf("\\");
		if(dirIndex == -1 && dirIndex2 == -1){
			System.err.println("文件路径非法...");
			return;
		}			
		int lastIndex = filePath.lastIndexOf("/");		
		String dirs = filePath.substring(0,lastIndex);		
		File file = new File(dirs);
		if(file.exists()){
			System.err.println("文件路径不用创建..."+dirs);
			return;
		}
		
		if(file.mkdirs()){
			System.out.println("文件目录创建成功..." + dirs);
		}else{
			System.out.println("文件目录创建失败..." + dirs);
		}
		file = new File(filePath);
		if(!file.exists()){
			file.createNewFile();
			System.out.println("文件目录及文件成功..." + filePath);
		}else{
			System.out.println("文件目录及文件已经存在");
		}
		
		
	}

	private static void copyFileToNio(File sourceFile, String newFilePath)
			throws IOException {
		 long timeStar = System.currentTimeMillis();//得到当前的时间
		FileInputStream fileInputStream = new FileInputStream(sourceFile);
		FileOutputStream fileOutputStream = new FileOutputStream(newFilePath);
		FileChannel inChannel = fileInputStream.getChannel();
		FileChannel outChannel = fileOutputStream.getChannel();		
		ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1024);
		while (true) {
			int eof = inChannel.read(byteBuffer);
			if (eof == -1)
				break;
			byteBuffer.flip();
			outChannel.write(byteBuffer);
			byteBuffer.clear();
		}
		inChannel.close();
		outChannel.close();
		if(new File(newFilePath).exists()){
			System.out.println("文件创建成功!");
		}else{
			System.out.println("文件创建失败!");
		}
	  long timeEnd = System.currentTimeMillis();//得到当前的时间
      System.out.println("Read time :" + (timeEnd - timeStar) + "ms");
		
	}

}

最新参考资料
JAVA NIO 简介 http://alicsd.iteye.com/blog/834447
引用以上链接:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class CopyFile {   
    public static void main(String[] args) throws Exception {   
        String infile = "C:\\copy.sql";   
        String outfile = "C:\\copy.txt";   
        // 获取源文件和目标文件的输入输出流   
        FileInputStream fin = new FileInputStream(infile);   
        FileOutputStream fout = new FileOutputStream(outfile);   
        // 获取输入输出通道   
        FileChannel fcin = fin.getChannel();   
        FileChannel fcout = fout.getChannel();   
        // 创建缓冲区   
        ByteBuffer buffer = ByteBuffer.allocate(1024);   
        while (true) {   
            // clear方法重设缓冲区,使它可以接受读入的数据   
            buffer.clear();   
            // 从输入通道中将数据读到缓冲区   
            int r = fcin.read(buffer);   
            // read方法返回读取的字节数,可能为零,如果该通道已到达流的末尾,则返回-1   
            if (r == -1) {   
                break;   
            }   
            // flip方法让缓冲区可以将新读入的数据写入另一个通道   
            buffer.flip();   
            // 从输出通道中将数据写入缓冲区   
            fcout.write(buffer);   
        }   
    }   
}
 

import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.net.InetSocketAddress;
import java.io.IOException;

public class BaiduReader {
	
	private Charset charset = Charset.forName("GBK");// 创建GBK字符集
	private SocketChannel channel;

	public void readHTMLContent() {
		try {
			InetSocketAddress socketAddress = new InetSocketAddress(
					"www.baidu.com", 80);
			// step1:打开连接
			channel = SocketChannel.open(socketAddress);
			// step2:发送请求,使用GBK编码
			channel.write(charset.encode("GET " + "/ HTTP/1.1" + "\r\n\r\n"));
			// step3:读取数据
			ByteBuffer buffer = ByteBuffer.allocate(1024);// 创建1024字节的缓冲
			while (channel.read(buffer) != -1) {
				buffer.flip();// flip方法在读缓冲区字节操作之前调用。
				System.out.println(charset.decode(buffer));
				// 使用Charset.decode方法将字节转换为字符串
				buffer.clear();// 清空缓冲
			}
		} catch (IOException e) {
			System.err.println(e.toString());
		} finally {
			if (channel != null) {
				try {
					channel.close();
				} catch (IOException e) {
				}
			}
		}
	}

	public static void main(String[] args) {
		new BaiduReader().readHTMLContent();
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics