簡體   English   中英

讀取文件和解析每一行的有效方法

[英]Effective way to read file and parse each line

我有一個下一種格式的文本文件:每行以一個字符串開頭,然后是數字序列。 每行的長度未知(數字數量未知,數量從0到1000)。

string_1 3 90 12 0 3
string_2 49 0 12 94 13 8 38 1 95 3
.......
string_n 9 43

之后,我必須使用handleLine方法處理每一行, handleLine方法接受兩個參數:字符串名稱和數字集( 請參見下面的代碼 )。

如何讀取文件並使用handleLine有效處理每一行?

我的解決方法:

  1. 使用java8流Files.lines讀取文件。 阻塞了嗎?
  2. 用正則表達式分割每一行
  3. 將每一行轉換為標題字符串和數字集

我認為由於第2步和第3步,它幾乎沒有效果。 第一步意味着java首先將文件字節轉換為字符串,然后在第二和第三步中將它們轉換回String / Set<Integer> 這對性能有很大影響嗎? 如果是,如何做得更好?

public handleFile(String filePath) {
    try (Stream<String> stream = Files.lines(Paths.get(filePath))) {
        stream.forEach(this::indexLine);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private void handleLine(String line) {
    List<String> resultList = this.parse(line);
    String string_i = resultList.remove(0);
    Set<Integer> numbers = resultList.stream().map(Integer::valueOf).collect(Collectors.toSet());
    handleLine(string_i, numbers); // Here is te final computation which must to be done only with string_i & numbers arguments
}

private List<String> parse(String str) {
    List<String> output = new LinkedList<String>();
    Matcher match = Pattern.compile("[0-9]+|[a-z]+|[A-Z]+").matcher(str);
    while (match.find()) {
        output.add(match.group());
    }
    return output;
}

關於第一個問題,這取決於您如何引用Stream Streams本質上是惰性的,並且如果您不打算使用它,則不會工作。 例如,對Files.lines的調用實際上不會讀取文件,除非您在Stream上添加了終端操作。

從Java文檔中:

從文件中讀取所有行作為流。 與readAllLines不同,此方法不會將所有行讀取到List中,而是在消耗流時延遲填充

forEach(Consumer<T>)調用是一個終端操作,在那一點上,文件的各indexLine被逐一讀取並傳遞給indexLine方法。

關於您的其他評論,您實際上在這里沒有任何問題。 您正在嘗試測量/最小化什么? 僅僅因為某件事是多個步驟並不能使它本身具有較差的性能。 即使您創建了一個wizbang oneliner來直接從File字節轉換為StringSet ,您也可能只是匿名進行了中間映射,或者您已經調用了某種東西,無論如何它都會使編譯器執行此操作。

這是將行解析為名稱和數字的代碼

stream.forEach(line -> {
    String[] split = line.split("\\b"); //split with blank seperator
    Set<String> numbers = IntStream.range(1, split.length)
                                .mapToObj(index -> split[index])
                                .filter(str -> str.matches("\\d+")) //filter numbers
                                .collect(Collectors.toSet());
    handleLine(split[0], numbers);
});

或另一種方式

Map<Boolean, List<String>> collect = Pattern.compile("\\b")
                                            .splitAsStream(line)
                                            .filter(str -> !str.matches("\\b"))
                                            .collect(Collectors.groupingBy(str -> str.matches("\\d+")));
handleLine(collect.get(Boolean.FALSE).get(0), collect.get(Boolean.TRUE));

我着手測試解決此問題的幾種方法,並在注明的條件下盡我所能來評估性能。 這是我測試的方法以及測試方法,以及隨附的結果:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class App {

    public static void method1(String testFile) {
        List<Integer> nums = null;
        try (Scanner s = new Scanner(Paths.get(testFile))) {
            while (s.hasNext()) {
                if (s.hasNextInt())
                    nums.add(s.nextInt());
                else {
                    nums = new ArrayList<Integer>();
                    String pre = s.next();
                    // handleLine( s.next() ... nums ... );
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void method2(String testFile) {
        List<Integer> nums = null;
        try (BufferedReader in = new BufferedReader(new FileReader(testFile));
                Scanner s = new Scanner(in)) {
            while (s.hasNext()) {
                if (s.hasNextInt())
                    nums.add(s.nextInt());
                else {
                    nums = new ArrayList<Integer>();
                    String pre = s.next();
                    // handleLine( s.next() ... nums ... );
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void method3(String testFile) {
        List<Integer> nums = null;
        try (BufferedReader br = new BufferedReader(new FileReader(testFile))) {
            String line = null;
            while ((line = br.readLine()) != null) {
                String[] arr = line.split(" ");
                nums = new ArrayList<Integer>();
                for (int i = 1; i < arr.length; ++i)
                    nums.add(Integer.valueOf(arr[i]));
                // handleLine( ... );
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void method3_1(String testFile) {
        List<Integer> nums = null;
        try (BufferedReader br = new BufferedReader(new FileReader(testFile))) {
            String line = null;
            while ((line = br.readLine()) != null) {
                String[] arr = line.split(" ");
                nums = new ArrayList<Integer>();
                for (int i = 1; i < arr.length; ++i)
                    nums.add(Integer.parseInt(arr[i]));
                // handleLine( ... );
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void method4(String testFile) {
        List<Integer> nums = null;
        try {
            List<String> lines = Files.readAllLines(Paths.get(testFile));
            for (String s : lines) {
                String[] arr = s.split(" ");
                nums = new ArrayList<Integer>();
                for (int i = 1; i < arr.length; ++i)
                    nums.add(Integer.valueOf(arr[i]));
                // handleLine( ... );
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void method4_1(String testFile) {
        List<Integer> nums = null;
        try {
            List<String> lines = Files.readAllLines(Paths.get(testFile));
            for (String s : lines) {
                String[] arr = s.split(" ");
                nums = new ArrayList<Integer>();
                for (int i = 1; i < arr.length; ++i)
                    nums.add(Integer.parseInt(arr[i]));
                // handleLine( ... );
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void method5(String testFile) {
        List<Integer> nums = null;
        try (BufferedReader br = Files.newBufferedReader(Paths.get(testFile))) {
            List<String> lines = br.lines().collect(Collectors.toList());
            for (String s : lines) {
                String[] arr = s.split(" ");
                nums = new ArrayList<Integer>();
                for (int i = 1; i < arr.length; ++i)
                    nums.add(Integer.valueOf(arr[i]));
                // handleLine( ... );
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void method5_1(String testFile) {
        List<Integer> nums = null;
        try (BufferedReader br = Files.newBufferedReader(Paths.get(testFile))) {
            List<String> lines = br.lines().collect(Collectors.toList());
            for (String s : lines) {
                String[] arr = s.split(" ");
                nums = new ArrayList<Integer>();
                for (int i = 1; i < arr.length; ++i)
                    nums.add(Integer.parseInt(arr[i]));
                // handleLine( ... );
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void method6(String testFile) {
        List<Integer> nums = new LinkedList<Integer>();
        try (Stream<String> stream = Files.lines(Paths.get(testFile))) {
            stream.forEach(line -> {
                String[] split = line.split("\\b"); // split with blank seperator
                Set<String> numbers = IntStream.range(1, split.length)
                        .mapToObj(index -> split[index])
                        .filter(str -> str.matches("\\d+")) // filter numbers
                        .collect(Collectors.toSet());
                numbers.forEach((k) -> nums.add(Integer.parseInt(k)));
                // handleLine( ... );
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {

        args = new String[] { "C:\\Users\\Nick\\Desktop\\test.txt" };

        Random r = new Random();

        System.out.println("warming up a little...");
        for (int i = 0; i < 100000; ++i) {
            int x = r.nextInt();
        }

        long s1 = System.currentTimeMillis();
        for (int i = 0; i < 10000; ++i)
            method1(args[0]);
        long e1 = System.currentTimeMillis();

        long s2 = System.currentTimeMillis();
        for (int i = 0; i < 10000; ++i)
            method2(args[0]);
        long e2 = System.currentTimeMillis();

        long s3 = System.currentTimeMillis();
        for (int i = 0; i < 10000; ++i)
            method3(args[0]);
        long e3 = System.currentTimeMillis();

        long s3_1 = System.currentTimeMillis();
        for (int i = 0; i < 10000; ++i)
            method3_1(args[0]);
        long e3_1 = System.currentTimeMillis();

        long s4 = System.currentTimeMillis();
        for (int i = 0; i < 10000; ++i)
            method4(args[0]);
        long e4 = System.currentTimeMillis();

        long s4_1 = System.currentTimeMillis();
        for (int i = 0; i < 10000; ++i)
            method4_1(args[0]);
        long e4_1 = System.currentTimeMillis();

        long s5 = System.currentTimeMillis();
        for (int i = 0; i < 10000; ++i)
            method5(args[0]);
        long e5 = System.currentTimeMillis();

        long s5_1 = System.currentTimeMillis();
        for (int i = 0; i < 10000; ++i)
            method5_1(args[0]);
        long e5_1 = System.currentTimeMillis();

        long s6 = System.currentTimeMillis();
        for (int i = 0; i < 10000; ++i)
            method6(args[0]);
        long e6 = System.currentTimeMillis();

        System.out.println("method 1 = " + (e1 - s1) + " ms");
        System.out.println("method 2 = " + (e2 - s2) + " ms");
        System.out.println("method 3 = " + (e3 - s3) + " ms");
        System.out.println("method 3_1 = " + (e3_1 - s3_1) + " ms");
        System.out.println("method 4 = " + (e4 - s4) + " ms");
        System.out.println("method 4_1 = " + (e4_1 - s4_1) + " ms");
        System.out.println("method 5 = " + (e5 - s5) + " ms");
        System.out.println("method 5_1 = " + (e5_1 - s5_1) + " ms");
        System.out.println("method 6 = " + (e6 - s6) + " ms");
    }
}
  • 與java.version = 1.8.0_101( Oracle )一起使用
  • x64操作系統/處理器

結果輸出:

warming up a little...
method 1 = 1103 ms
method 2 = 872 ms
method 3 = 440 ms
method 3_1 = 418 ms
method 4 = 413 ms
method 4_1 = 376 ms
method 5 = 439 ms
method 5_1 = 384 ms
method 6 = 646 ms

據我了解,我測試的樣本中最好的方法是使用Files.readAllLiness.split(" ")Integer.parseInt 在我使用並創建並測試的樣本中,這三種組合顯然再次產生了最快的速度至少您可能會改用Integer.parseInt有所幫助。

注意我使用資源來幫助獲得一些受歡迎的方法,並將其應用於該問題/示例。 例如, 這篇博客文章本教程以及這個很棒的家伙@ Peter-Lawrey 此外, 始終可以進行進一步的改進

另外,test.txt文件:

my_name 15 00 29 101 1234
cool_id 11 00 01 10 010101
longer_id_name 1234
dynamic_er 1 2 3 4 5 6 7 8 9 10 11 12 123 1456 15689 555555555

(注意:性能可能會因文件大小而有很大差異!)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM