2016-10-24 39 views
1

我有一个下一个格式的文本文件:每一行都以字符串开头,后面跟着数字序列。每行有未知长度(未知数量,数量从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

我的解决方法:

  1. 逐行读取文件中的行与java8流Files.lines它阻塞了吗?
  2. 拆分与正则表达式的每一行
  3. 将每个行成头字符串,并设置数字

我认为这是非常uneffective由于第二和第三个步骤。第一步意味着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; 
} 
+1

正如建议,也许移动Pattern.compile这种方法之外,我认为你不需要为每一行编译相同的模式。 – eg04lt3r

回答

3

关于你的第一个问题,这取决于你如何引用StreamStreams本质上是懒惰的,如果你不打算使用它,就不会工作。例如,在Stream上添加终端操作之前,调用Files.lines实际上不会读取该文件。

从Java文档:

从文件中读取的一个流的所有行。不像readAllLines,这种方法不读取所有线到一个列表,而是填充懒惰地作为流被消耗

forEach(Consumer<T>)呼叫是一个终端的操作,并且,在这一点上,该文件的行被读出一个一个地传递给你的indexLine方法。

关于你的其他意见,你在这里没有问题。你想要测量/最小化什么?仅仅因为某些事情是多个步骤本身并不会使其表现不佳。即使您创建了一个wizbang oneliner,将File字节直接转换为您的String & Set,但您可能只是匿名执行了中间映射,或者您已经调用了一些能够使编译器无论如何都这样做的东西。

1

这里是你的代码来解析线为名字和号码

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)); 
1

我的目标是测试几种方式去了解这个问题,并衡量性能最佳我可以在特定条件下工作。下面是我测试过,我怎么测试它,并结合结果一起:

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以提供某些帮助。

注意我使用源来帮助获得一些追求方法并将它们应用于此问题/示例。例如。 this blog post,this tutorial,和这个真棒伙计@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 

(注:性能取决于文件大小可能相差很大)

+0

相当有用的测试,谢谢! –

相关问题