`

NIO - FileChannel

 
阅读更多

转自:http://blog.csdn.net/java2000_wl/article/details/7614611

 

  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.FileNotFoundException;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.io.OutputStream;  
  8. import java.nio.ByteBuffer;  
  9. import java.nio.channels.Channel;  
  10. import java.nio.channels.FileChannel;  
  11. import java.nio.charset.Charset;  
  12.   
  13. public class FileChannelMain {  
  14.       
  15.     private static final Charset charset = Charset.forName("GBK");  
  16.       
  17.     private static final int BUFFER_CAPACITY  = 1024;  
  18.       
  19.     public static void main(String[] args) throws IOException, InterruptedException {  
  20.         final String srcfilePath = "D:/tomcat-6.0.26/logs/catalina.2012-04-30.log";  
  21.         readFile(srcfilePath);  
  22.           
  23.         final String writeFilePath = "D:/test.txt";  
  24.         final String[] lines = new String[]{"line1xxssss""中文测试""!@#$%^&*()"};   
  25.         writeFile(writeFilePath, lines, Boolean.TRUE);  
  26.         readFile(writeFilePath);  
  27.           
  28.         final String targetFilePath = "D:/test-copy.txt";  
  29.         copyFile1(srcfilePath, targetFilePath);  
  30.         copyFile2(srcfilePath, targetFilePath);  
  31.     }  
  32.   
  33.     /** 
  34.      * 
  35.      * <br>------------------------------<br> 
  36.      * @param srcfilePath 
  37.      * @param targetPath 
  38.      * @throws IOException  
  39.      */  
  40.     private static void copyFile2(String srcfilePath, String targetPath) throws IOException {  
  41.         File file = new File(targetPath);  
  42.         if (!file.getParentFile().exists()) {  
  43.             file.mkdirs();  
  44.         }  
  45.         FileInputStream fileInputStream = new FileInputStream(srcfilePath);  
  46.         FileOutputStream fileOutputStream = new FileOutputStream(file);  
  47.         FileChannel inChannel = fileInputStream.getChannel();  
  48.         FileChannel outChannel = fileOutputStream.getChannel();  
  49.         //两者等价  
  50. //      inChannel.transferTo(0, inChannel.size(), outChannel);  
  51.         outChannel.transferFrom(inChannel, 0, inChannel.size());  
  52.           
  53.         close(fileOutputStream);  
  54.         close(fileInputStream);  
  55.         close(inChannel);  
  56.         close(outChannel);  
  57.     }  
  58.   
  59.     /** 
  60.      * 
  61.      * <br>------------------------------<br> 
  62.      * @param srcfilePath 
  63.      * @param targetPath 
  64.      * @throws IOException  
  65.      */  
  66.     private static void copyFile1(String srcfilePath, String targetPath) throws IOException {  
  67.         File file = new File(targetPath);  
  68.         if (!file.getParentFile().exists()) {  
  69.             file.mkdirs();  
  70.         }  
  71.         FileInputStream fileInputStream = new FileInputStream(srcfilePath);  
  72.         FileOutputStream fileOutputStream = new FileOutputStream(file);  
  73.         FileChannel inChannel = fileInputStream.getChannel();  
  74.         FileChannel outChannel = fileOutputStream.getChannel();  
  75.         ByteBuffer inBuffer = ByteBuffer.allocate(BUFFER_CAPACITY);  
  76.         while (inChannel.read(inBuffer) != -1) {  
  77.             inBuffer.flip();  
  78.             outChannel.write(inBuffer);  
  79.             inBuffer.clear();  
  80.         }  
  81.         close(fileOutputStream);  
  82.         close(fileInputStream);  
  83.         close(inChannel);  
  84.         close(outChannel);  
  85.     }  
  86.   
  87.     /** 
  88.      * <br>------------------------------<br> 
  89.      * @param writeFilePath 
  90.      * @param lines 
  91.      * @param append 
  92.      * @throws IOException 
  93.      */  
  94.     private static void writeFile(String writeFilePath, String[] lines, boolean append) throws IOException {  
  95.         File file = new File(writeFilePath);  
  96.         if (!file.getParentFile().exists()) {  
  97.             file.mkdirs();  
  98.         }  
  99.         FileOutputStream fileOutputStream = new FileOutputStream(file, append);  
  100.         FileChannel fileChannel = fileOutputStream.getChannel();  
  101.         ByteBuffer buffer = ByteBuffer.allocate(BUFFER_CAPACITY);  
  102.         for (String line : lines) {  
  103.             buffer.put(line.getBytes());  
  104.             buffer.put("\r\n".getBytes());  
  105.             buffer.flip();  
  106.             fileChannel.write(buffer);  
  107.             buffer.clear();  
  108.         }  
  109.         close(fileOutputStream);  
  110.         close(fileChannel);  
  111.     }  
  112.       
  113.     /** 
  114.      * <br>------------------------------<br> 
  115.      * @param path 
  116.      * @throws IOException 
  117.      */  
  118.     private static void readFile(String path) throws IOException {  
  119.         if (isFileNotExists(path)) {  
  120.             throw new FileNotFoundException();  
  121.         }  
  122.         FileInputStream fileInputStream = new FileInputStream(path);  
  123.         FileChannel fileChanne = fileInputStream.getChannel();  
  124.         ByteBuffer buffer = ByteBuffer.allocate(BUFFER_CAPACITY);  
  125.         while (fileChanne.read(buffer) != -1) {  
  126.             buffer.flip();  
  127.             System.out.println(charset.decode(buffer));  
  128.             buffer.clear();  
  129.         }  
  130.         close(fileInputStream);  
  131.         close(fileChanne);  
  132.     }  
  133.       
  134.     private static boolean isFileNotExists(String path) {  
  135.         File file = new File(path);  
  136.         return !file.exists();  
  137.     }  
  138.       
  139.     /** 
  140.      *  
  141.      * <br>------------------------------<br> 
  142.      * @param outputStream 
  143.      */  
  144.     private static void close(OutputStream outputStream) {  
  145.         if (outputStream == nullreturn;  
  146.         try {  
  147.             outputStream.close();  
  148.         } catch (IOException e) {  
  149.             e.printStackTrace();  
  150.         }  
  151.     }  
  152.       
  153.     /** 
  154.      *  
  155.      * <br>------------------------------<br> 
  156.      * @param channel 
  157.      */  
  158.     private static void close(Channel channel) {  
  159.         if (channel == null ) return;  
  160.         try {  
  161.             channel.close();  
  162.         } catch (IOException e) {  
  163.             e.printStackTrace();  
  164.         }  
  165.     }  
  166.       
  167.     /** 
  168.      *  
  169.      * <br>------------------------------<br> 
  170.      * @param inputStream 
  171.      */  
  172.     private static void close(InputStream inputStream) {  
  173.         if (inputStream == nullreturn;  
  174.         try {  
  175.             inputStream.close();  
  176.         } catch (IOException e) {  
  177.             e.printStackTrace();  
  178.         }  
  179.     }  

分享到:
评论

相关推荐

    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