Java代码如何读取本地文件呢?

书欣 Java经验 发布时间:2023-01-03 15:11:03 阅读数:5795 1
下文笔者讲述使用Java代码读取本地文件的三种方法分享,如下所示
实现思路:
    使用InputStreamReader
	使用NIO读取本地文件
    使用MappedByteBuffer读取本地文件

1、java读取按行本地txt文件

    public static void readTxt(String filePath) {
        try {
            File file = new File(filePath);
            if(file.isFile() && file.exists()) {
                InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
                BufferedReader br = new BufferedReader(isr);
                String lineTxt = null;
                int num =0;
                long time1 = System.currentTimeMillis();
                while ((lineTxt = br.readLine()) != null) {
                    System.out.println(lineTxt);
                    num++;
                    System.out.println("总共"+num+"条数据!");
                }
                //System.out.println("总共"+num+"条数据!");
                long time2 = System.currentTimeMillis();
                long time = time1 - time2;
                System.out.println("共花费"+time+"秒");
                br.close();
            } else {
                System.out.println("文件不存在!");
            }
        } catch (Exception e) {
            System.out.println("文件读取错误!");
        }
    }


    public static void main(String[] args) {
        String filePath = "/logs/test.txt";
        System.out.println(filePath);
        readTxt(filePath);
    }
 

java的NIO按行读取本地文件

    public static void readTxtByNIO(String filePath) {
        long time1 = System.currentTimeMillis();
        FileInputStream fis = null;
        FileChannel inChannel = null;
        int bufSize = 1024*10;
        try {
            fis = new FileInputStream(filePath);
            inChannel = fis.getChannel();
            System.out.println("file size --->"+inChannel.size());
            ByteBuffer buffer = ByteBuffer.allocate(bufSize);
           // System.out.println("buffer init position --->"+buffer.position()+"---- buffer init remaining --->"+buffer.remaining());
            //这里标记了后面才可以调用buffer.reset(), 而且只能调用一次,
            //不然会抛出java.nio.InvalidMarkException
            //buffer.mark();
            String enterStr = "\n";
            StringBuffer strBuf = new StringBuffer("");
            int lineNum = 0;
            while(inChannel.read(buffer) != -1){
                int rSize = buffer.position();
                buffer.clear();
                String tempString = new String(buffer.array(), 0, rSize);
                if(fis.available() ==0){//最后一行,加入"\n分割符"
                    tempString+="\n";
                }

                int fromIndex = 0;

                int endIndex = 0;
                while ((endIndex = tempString.indexOf(enterStr, fromIndex)) != -1) {

                    String line = tempString.substring(fromIndex, endIndex);

                    line = new String(strBuf.toString() + line);

                    System.out.println(line);

                    strBuf.delete(0, strBuf.length());

                    fromIndex = endIndex + 1;
                    lineNum++;
                }

                if (rSize > tempString.length()) {

                    strBuf.append(tempString.substring(fromIndex, tempString.length()));

                } else {
                    strBuf.append(tempString.substring(fromIndex, rSize));

                }
                System.out.println("lineNum ="+ lineNum);
            }
        } catch (Exception e) {
            System.out.println("文件读取错误!");
        } finally {
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(inChannel != null){
                try{
                    inChannel.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }

            long time2 = System.currentTimeMillis();
            long time = (time1-time2)/1000;
            System.out.println("共花费"+time+"秒");
        }
    }

   public static void main(String[] args) {
        String filePath = "/logs/test.txt";
        System.out.println(filePath);
        readTxtByBuffer(filePath);
    }
 

MappedByteBuffer

package com.java265;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.list;

public class importTest2 {

    public static void main(String[] args) {
        String filePath = "/logs/test1.txt";
        String filePath1 = "/logs2/test2.txt";
        System.out.println(filePath1);
        readTxt(filePath);
    }

    static int length = 0x8000000; // 128 Mb
    public static void readTxt(String filePath){
        long timeStar = System.currentTimeMillis();// 得到当前的时间
        File file = new File(filePath);
        importTest2 mf = new importTest2();
        try {
            mf.structXML(file);
        } catch (Exception e) {
            System.out.println("文件读取错误!");
            e.printStackTrace();
        } finally {

            long timeEnd = System.currentTimeMillis();
            long time = (timeEnd-timeStar);
            System.out.println("共花费"+time+"ms");
        }


    }

    private List structXML(File file) throws IOException{
        try {
            if(file.length()<length){
                length = (int)file.length();
            }
            MappedByteBuffer buffer = new RandomAccessFile(file, "r")
                    .getChannel().map(FileChannel.MapMode.READ_ONLY,
                            0, length);
            new Thread(new CompareThread(buffer)).start();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    class CompareThread implements Runnable{
        private MappedByteBuffer buffer = null;
        final int BUFFER_SIZE = 0x1000;
        byte[] dst = new byte[BUFFER_SIZE];

        public CompareThread(MappedByteBuffer buffer) {
            this.buffer = buffer;
        }

        public void run(){
            long start = System.currentTimeMillis();
            String enterStr = "\n";
            StringBuffer strBuf = new StringBuffer("");
            long total=0;
            for (int offset = 0; offset < this.buffer.capacity(); offset += BUFFER_SIZE) {
                if (this.buffer.capacity() - offset >= BUFFER_SIZE) {
                    for (int i = 0; i < BUFFER_SIZE; i++)
                        dst[i] = this.buffer.get(offset + i);
                } else {
                    for (int i = 0; i < this.buffer.capacity() - offset; i++)
                        dst[i] = this.buffer.get(offset + i);
                }
                int length = (this.buffer.capacity() % BUFFER_SIZE == 0) ? BUFFER_SIZE
                        : this.buffer.capacity() % BUFFER_SIZE;
                String tempString = new String(dst, 0, length);
                int fromIndex = 0;
                int endIndex = 0;
                while ((endIndex = tempString.indexOf(enterStr, fromIndex)) != -1) {
                    total++;
                    String line = tempString.substring(fromIndex, endIndex);
                    line = new String(strBuf.toString() + line); 
                    fromIndex = endIndex + 1;
                    strBuf.delete(0, strBuf.length());
                }
            }
            System.out.println("total----->"+total+"====耗时==="+(System.currentTimeMillis()-start));
        }
    }
}
 
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202301/16727307935276.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者