旗下导航:搜·么
当前位置:网站首页 > JAVA教程 > 正文

java中怎样读取文件?【JAVA教程】,java

作者:搜教程发布时间:2019-12-04分类:JAVA教程浏览:50评论:0


导读:读取文件有多种体式格局,基于传统的输入流体式格局或基于nio的Buffer缓冲对象和管道读取体式格局以至异常疾速的内存映照读取文件。java中四种读取文件体式格局:(引...

读取文件有多种体式格局,基于传统的输入流体式格局或基于nio的Buffer缓冲对象和管道读取体式格局以至异常疾速的内存映照读取文件。

java中四种读取文件体式格局:(引荐:java视频教程)

1、RandomAccessFile:随机读取,比较慢长处就是该类可读可写可操纵文件指针

2、FileInputStream:io平常输入流体式格局,速率效力平常

3、Buffer缓冲读取:基于nio Buffer和FileChannel读取,速率较快

4、内存映照读取:基于MappedByteBuffer,速率最快

RandomAccessFile读取

//RandomAccessFile类的中心在于其既能读又能写

public void useRandomAccessFileTest() throws Exception {

    RandomAccessFile randomAccessFile = new RandomAccessFile(new File("e:/nio/test.txt"), "r");

    byte[] bytes = new byte[1024];
    int len = 0;
    while ((len = randomAccessFile.read(bytes)) != -1) {
        System.out.println(new String(bytes, 0, len, "gbk"));
    }

    randomAccessFile.close();
}

FielInputStream读取

//运用FileInputStream文件输入流,比较中规中矩的一种体式格局,传统壅塞IO操纵。

public void testFielInputStreamTest() throws Exception {

    FileInputStream inputStream = new FileInputStream(new File("e:/nio/test.txt"));

    // 运用输入流读取文件,以下代码块险些就是模板代码
    byte[] bytes = new byte[1024];
    int len = 0;
    while ((len = inputStream.read(bytes)) != -1) {// 如果有数据就一向读写,不然就退出循环体,封闭流资本。
        System.out.println(new String(bytes, 0, len, "gbk"));
    }
    inputStream.close();
}

Buffer缓冲对象读取

// nio 读取

public void testBufferChannel() throws Exception {

    FileInputStream inputStream = new FileInputStream(new File("e:/nio/test.txt"));

    FileChannel fileChannel = inputStream.getChannel();
    ByteBuffer buffer = ByteBuffer.allocate(1024);

    // 以下代码也险些是Buffer和Channle的规范读写操纵。
    while (true) {
        buffer.clear();
        int result = fileChannel.read(buffer);
        buffer.flip();
        if (result == -1) {
            break;
        }
        System.out.println(new String(buffer.array(), 0, result, "gbk"));
    }
    inputStream.close();
}

内存映照读取

public void testmappedByteBuffer() throws Exception {

    FileInputStream inputStream = new FileInputStream(new File("e:/nio/test.txt"));
    FileOutputStream outputStream = new FileOutputStream(new File("e:/nio/testcopy.txt"),true);

    FileChannel inChannel = inputStream.getChannel();
    FileChannel outChannel = outputStream.getChannel();

    System.out.println(inChannel.size());
    MappedByteBuffer mappedByteBuffer = inChannel.map(MapMode.READ_ONLY, 0, inChannel.size());

    System.out.println(mappedByteBuffer.limit());
    System.out.println(mappedByteBuffer.position());

    mappedByteBuffer.flip();
    outChannel.write(mappedByteBuffer);

    outChannel.close();
    inChannel.close();
    outputStream.close();
    inputStream.close();

}

//基于内存映照这类体式格局,这么写彷佛有问题。


MappedByteBuffer和RandomAcessFile这两个类要零丁重点研究一下。

//TODO 大文件读取

更多java学问请关注java基础教程栏目。

以上就是java中怎样读取文件?的细致内容,更多请关注ki4网别的相干文章!

标签:java


欢迎 发表评论: