>  기사  >  Java  >  Java에서 파일을 읽는 방법은 무엇입니까?

Java에서 파일을 읽는 방법은 무엇입니까?

尚
원래의
2019-12-04 10:01:054567검색

Java에서 파일을 읽는 방법은 무엇입니까?

파일을 읽는 방법에는 전통적인 입력 스트림 방법이나 nio 기반 버퍼 개체 및 파이프 읽기 방법, 심지어 매우 빠른 메모리 매핑을 기반으로 파일을 읽는 방법 등 여러 가지가 있습니다.

Java에서 파일을 읽는 네 가지 방법: (권장: java 비디오 튜토리얼)

1. RandomAccessFile: 무작위 읽기, 상대적으로 느림 장점은 이러한 유형의 읽기, 쓰기 및 작동 가능 파일 포인터

2입니다. : io 일반 입력 스트림 모드, 속도 및 효율성은 평균입니다

3. 버퍼 버퍼 읽기: nio 버퍼 및 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();
}

버퍼 버퍼 객체 읽기

// 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에서 파일을 읽는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.