`
lovnet
  • 浏览: 6710209 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
文章分类
社区版块
存档分类
最新评论

NIO - FileChannel

 
阅读更多
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

public class FileChannelMain {
	
	private static final Charset charset = Charset.forName("GBK");
	
	private static final int BUFFER_CAPACITY  = 1024;
	
	public static void main(String[] args) throws IOException, InterruptedException {
		final String srcfilePath = "D:/tomcat-6.0.26/logs/catalina.2012-04-30.log";
		readFile(srcfilePath);
		
		final String writeFilePath = "D:/test.txt";
		final String[] lines = new String[]{"line1xxssss", "中文测试", "!@#$%^&*()"}; 
		writeFile(writeFilePath, lines, Boolean.TRUE);
		readFile(writeFilePath);
		
		final String targetFilePath = "D:/test-copy.txt";
		copyFile1(srcfilePath, targetFilePath);
		copyFile2(srcfilePath, targetFilePath);
	}

	/**
	 *
	 * <br>------------------------------<br>
	 * @param srcfilePath
	 * @param targetPath
	 * @throws IOException 
	 */
	private static void copyFile2(String srcfilePath, String targetPath) throws IOException {
		File file = new File(targetPath);
		if (!file.getParentFile().exists()) {
			file.mkdirs();
		}
		FileInputStream fileInputStream = new FileInputStream(srcfilePath);
		FileOutputStream fileOutputStream = new FileOutputStream(file);
		FileChannel inChannel = fileInputStream.getChannel();
		FileChannel outChannel = fileOutputStream.getChannel();
		//两者等价
//		inChannel.transferTo(0, inChannel.size(), outChannel);
		outChannel.transferFrom(inChannel, 0, inChannel.size());
		
		close(fileOutputStream);
		close(fileInputStream);
		close(inChannel);
		close(outChannel);
	}

	/**
	 *
	 * <br>------------------------------<br>
	 * @param srcfilePath
	 * @param targetPath
	 * @throws IOException 
	 */
	private static void copyFile1(String srcfilePath, String targetPath) throws IOException {
		File file = new File(targetPath);
		if (!file.getParentFile().exists()) {
			file.mkdirs();
		}
		FileInputStream fileInputStream = new FileInputStream(srcfilePath);
		FileOutputStream fileOutputStream = new FileOutputStream(file);
		FileChannel inChannel = fileInputStream.getChannel();
		FileChannel outChannel = fileOutputStream.getChannel();
		ByteBuffer inBuffer = ByteBuffer.allocate(BUFFER_CAPACITY);
		while (inChannel.read(inBuffer) != -1) {
			inBuffer.flip();
			outChannel.write(inBuffer);
			inBuffer.clear();
		}
		close(fileOutputStream);
		close(fileInputStream);
		close(inChannel);
		close(outChannel);
	}

	/**
	 * <br>------------------------------<br>
	 * @param writeFilePath
	 * @param lines
	 * @param append
	 * @throws IOException
	 */
	private static void writeFile(String writeFilePath, String[] lines, boolean append) throws IOException {
		File file = new File(writeFilePath);
		if (!file.getParentFile().exists()) {
			file.mkdirs();
		}
		FileOutputStream fileOutputStream = new FileOutputStream(file, append);
		FileChannel fileChannel = fileOutputStream.getChannel();
		ByteBuffer buffer = ByteBuffer.allocate(BUFFER_CAPACITY);
		for (String line : lines) {
			buffer.put(line.getBytes());
			buffer.put("\r\n".getBytes());
			buffer.flip();
			fileChannel.write(buffer);
			buffer.clear();
		}
		close(fileOutputStream);
		close(fileChannel);
	}
	
	/**
	 * <br>------------------------------<br>
	 * @param path
	 * @throws IOException
	 */
	private static void readFile(String path) throws IOException {
		if (isFileNotExists(path)) {
			throw new FileNotFoundException();
		}
		FileInputStream fileInputStream = new FileInputStream(path);
	 	FileChannel fileChanne = fileInputStream.getChannel();
	 	ByteBuffer buffer = ByteBuffer.allocate(BUFFER_CAPACITY);
	 	while (fileChanne.read(buffer) != -1) {
	 		buffer.flip();
	 		System.out.println(charset.decode(buffer));
	 		buffer.clear();
		}
	 	close(fileInputStream);
	 	close(fileChanne);
	}
	
	private static boolean isFileNotExists(String path) {
		File file = new File(path);
		return !file.exists();
	}
	
	/**
	 * 
	 * <br>------------------------------<br>
	 * @param outputStream
	 */
	private static void close(OutputStream outputStream) {
		if (outputStream == null) return;
		try {
			outputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * <br>------------------------------<br>
	 * @param channel
	 */
	private static void close(Channel channel) {
		if (channel == null ) return;
		try {
			channel.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * <br>------------------------------<br>
	 * @param inputStream
	 */
	private static void close(InputStream inputStream) {
		if (inputStream == null) return;
		try {
			inputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
分享到:
评论

相关推荐

    java网络编程NIO视频教程

    04-Java NIO-Channel-FileChannel(介绍和示例).mp4 05-Java NIO-Channel-FileChannel详解(一).mp4 06-Java NIO-Channel-FileChannel详解(二).mp4 07-Java NIO-Channel-Socket通道-概述.mp4 08-Java NIO-Channel-...

    Java NIO实战开发多人聊天室

    05-Java NIO-Channel-FileChannel详解(一).mp4 06-Java NIO-Channel-FileChannel详解(二).mp4 08-Java NIO-Channel-ServerSocketChannel.mp4 09-Java NIO-Channel-SocketChannel.mp4 10-Java NIO-Channel-...

    muyinchen#woker#07 Java的NIO之FileChannel1

    7.1 打开一个FileChannel 7.2 从FileChannel通道中读取数据 7.3 向FileChannel中写入数据: 7.4 关闭FileCha

    JavaNIO chm帮助文档

    Java NIO系列教程(七) FileChannel Java NIO系列教程(八) SocketChannel Java NIO系列教程(九) ServerSocketChannel Java NIO系列教程(十) Java NIO DatagramChannel Java NIO系列教程(十一) Pipe Java ...

    2021最新-Java NIO视频教程-视频教程网盘链接提取码下载 .txt

    教程内容涵盖:阻塞和非阻塞IO、Channel通道、Buffer缓冲区、Selector选择器、Pipe管道、FileLock文件锁,以及Path、Files、异步FileChannel和Charset字符编码等,并通过一个多人聊天室的综合案例,把所有的NIO知识...

    jruby-stdin-channel:JRuby 扩展为 STDIN 公开可中断的 NIO FileChannel

    jruby-stdin-channel JRuby Java 扩展 gem,它从 Java System.in stdin 中提取可中断的FileChannel。 使用这个 gem,在阻塞read方法上调用close将解除阻塞,这与普通的 JRuby $stdin 。 使用close转义阻塞读取仅适用...

    NIO(byteBuffer)按行读取文件

    使用nio byteBuffer 实现按行读取文件(大文件) 在window/linux/macOS上均测试通过 对于中文乱码也已处理成功 完整注释,可随需求更改 有问题请邮件:mly610865580@126.com

    mina:Java Nio Apache Mina Java Nio

    java-nio java-nio ...AbstractInterruptibleChannel, AbstractSelectableChannel, DatagramChannel, FileChannel, Pipe.SinkChannel, Pipe.SourceChannel, SelectableChannel, ServerSocketChannel, Socke

    01_尚硅谷_Java NIO_课件_V1.01

    1.1 阻塞 IO 2.3 FileChannel 介绍和示例 2.4 FileChannel 操作详解

    muyinchen#woker#06 Java的NIO之不同channel之间传输数据1

    两个通道之间传输数据的方式有两种,分别是:FileChannel 的transferFrom()方法可以将数据从源通道传输到FileChannel中(这个方法在

    编写一个java应用程序将一个包含多个子目录和文件的目录复制到另外一个指定的目录下

    import java.nio.channels.FileChannel; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import javax.swing.filechooser.FileFilter; 实验...

    JDK_seaswalker.tar.gz

    FileChannel Buffer URLConnection NIO Process HashMap LinkedHashMap TreeMap ConcurrentHashMap ConcurrentLinkedQueue ThreadPool ThreadLocal Reflection ScheduledThreadPool ...

    java二叉树源码-scodec-bits:提供用于处理位和字节的不可变数据类型

    源(如java.nio.channels.ReadableByteChannel和java.nio.channels.FileChannel一起使用的方法,它们允许对来自各种源的位和字节进行高效、惰性的访问和操作。 十六进制和二进制字符串字面量是通过所支持的hex和bin...

    tomcat-7_API_帮助文档

    There are some Linux bugs reported against the NIO sendfile behavior, make sure you have a JDK that is up to date, or disable sendfile behavior in the Connector. 6427312: (fc) FileChannel....

    sambox:一个PDFBox分支,打算用作Sejda和PDFsam的PDF处理程序

    SAMBox使用允许使用基于java.nio.channels.FileChannel , java.io.InputStream和java.nio.MappedByteBuffer的提供的实现之一(是否缓冲)。 通过使用java.lang.StringBuilder池最小化GC。 通过绑定视图的概念直接...

    java8源码-netty-learn:这是一个用于netty学习的工程

    ##NIO基础 三大组件 Channel & Buffer channel有点类似于stream,它就是读写数据的双向通道,可以从channel将数据读入buffer,也可以将buffer中的数据写入到channel 中,而stream只能完成一种 常见的Channel有 ...

    txt文档阅读器

    import java.nio.channels.FileChannel; import java.text.DecimalFormat; import java.util.Vector; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import ...

    ip地址库 很全的库

    import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /* * ...

    java pdf 查看器

    import java.nio.channels.FileChannel; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Box; import ...

Global site tag (gtag.js) - Google Analytics