JAVA读取数据

本文介绍了Java中三种读取文件的方法:1) 使用传统IO进行文件读取,2) 利用NIO(非阻塞I/O)进行文件操作,3) 通过Java 8的Stream API读取文本文件。对于Java NIO的深入理解,建议参考链接中的博客。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

读取文件

1.传统IO文件读取方式

package com.lyj.test2;

import java.io.*;

/**
 * Created by LYJ on 2016/10/9.
 * 传统读取文件的方式(按行读取)
 */
public class TestIO {
    public static void main(String... args) {
        String filePath="E:\\JAVA\\javaPrj\\TestNIOStream1\\resources\\qq.txt";
        String encoding = "utf-8";
        try {
            File file = new File(filePath);
            //通过输入流读取文件
            InputStreamReader read = new InputStreamReader(
                    new FileInputStream(file), encoding);// 考虑到编码格式
            BufferedReader bufferedReader = new BufferedReader(read);
            String lineTxt = null;
            //按行读取
            while ((lineTxt = bufferedReader.readLine()) != null) {
                System.out.println(lineTxt + "      --------- lineTxt    --- TestIO.main\n");
            }
            read.close();
        } catch (FileNotFoundException e) {
            System.out.println("找不到指定文件");
        }catch (IOException e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
    }
}

2.通过java NIO读取文件

package com.lyj.test2;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

/**
 * Created by LYJ on 2016/10/8.
 *    读写文件一般都使用该方法
 *
 *   分配空间(ByteBuffer buf = ByteBuffer.allocate(1024); 还有一种allocateDirector后面再陈述)
 *   写入数据到Buffer(int bytesRead = fileChannel.read(buf);)
 *   调用filp()方法( buf.flip();)
 *   从Buffer中读取数据(System.out.print((char)buf.get());)
 *   调用clear()方法或者compact()方法
 *
 *
 */
public class TestNIO
{
    public static void main(String... args){
        //设置编码,默认utf-8
        Charset charset=Charset.defaultCharset();
        //通过构造CharsetEncoder和CharsetDecoder将字符序列转换成字节和逆转换。
        CharsetDecoder decoder=charset.newDecoder();
        RandomAccessFile accessFile= null;
        ByteBuffer buf= null;
        CharBuffer charBuffer= null;
        int byteRead= 0;
        String path="E:\\JAVA\\javaPrj\\TestNIOStream1\\resources\\qq.txt";
        try {
            //通过RandomAccessFile读取文件
            accessFile = new RandomAccessFile(path,"rw");
            //读取文件到通道中
            FileChannel channel = accessFile.getChannel();
            //分配缓存区 accessFile.length()=channel.size()
            buf = ByteBuffer.allocate((int)accessFile.length());
            //如果含有中文字使用CharBuffer
            charBuffer = CharBuffer.allocate((int)channel.size());
            byteRead = channel.read(buf);
            //将通道中的数据写入到buffer,返回已读取的数量 -1表示已经到文件结尾
            while (byteRead!=-1){
                //flip()相当于截取文件长度,未写入数据的buffer被舍弃
                buf.flip();
                //逆转换   将字节转换成字符
                decoder.decode(buf,charBuffer,false);
                charBuffer.flip();

                //输出数据
                while (charBuffer.hasRemaining()){
                    System.out.print(charBuffer.get());
                }

                System.out.println();
                //最后调用buf.compact()或者buf.clear()方法
                //clear会把未读取的部分给覆盖掉
                //compact会把未读取的数据放到前面,从后面开始写入新的数据
                buf.compact();
                //buf.clear();
                charBuffer.compact();
                //charBuffer.clear();
                try {
                    byteRead=channel.read(buf);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        } catch (FileNotFoundException e) {
            System.out.println("找不到指定文件");
        }catch (IOException e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }finally {
            try {
                if (accessFile!=null){
                    accessFile.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


}

3.通过java8的StreamAPI读取文本文件

package com.lyj.test2;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

/**
 * Created by LYJ on 2016/10/8.
 *
 * 通过java8中的Stream API读取文件
 * 优点:更方便更简洁
 * 缺点:只能读取文本文件
 */
public class TestStream {
    public static void main(String... args){
        //定义路径
        Path path = Paths.get("E:\\JAVA\\javaPrj\\TestNIOStream1\\resources\\qq.txt");
        String content="";
        //通过Files.lines 读取 返回  Stream<Stream>
        try (Stream<String> lines = Files.lines(path, Charset.defaultCharset())) {
            //使用StreamAPI的归约操作 reduce(初始值,BinaryOperator<T>)
            //BinaryOperator<T>  (T,T)->T  将两个元素结合起来产生一个新值
            //这里我们用的是lambda表达式 (a,b)->a+b
            content=lines.reduce("",(line1,line2)->line1+"\n"+line2);
        } catch (NoSuchFileException e) {
            System.out.println("找不到指定文件");
        }catch (IOException e) {
            System.out.println("读取文件出错!");
            e.printStackTrace();
        }
        System.out.println(content + "      --------- content    --- TestStream.main\n");
    }
}
关于java NIO方面的内容可以参考这篇博客http://blog.youkuaiyun.com/u013256816/article/details/51457215
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值