2017-09-15 189 views
0

我对Java编程非常陌生。我需要以较小的块读取一个巨大的java文件。例如 如果我有如下文件如何使用java代码批量读取文件内容

a 
b 
c 
d 
e 
f 
g 
h 

我有批量大小为2按上面的文件我需要创建4批和然后过程。在这个任务中,我不需要有多线程模式。 以下是我所尝试过的。我知道这很简单,我已经接近我想要达到的目标。 上的代码的任何建议,将有助于

public class testing { 
public static void main(String[] args) throws IOException { 
    System.out.println("This is for testing"); 
    FileReader fr = null; 
    try { 
     fr = new FileReader("C:\\Users\\me\\Desktop\\Files.txt"); 
    } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    int batchSize=2; 
    int batchCount=0; 
    int lineIncr=0; 
    BufferedReader bfr = new BufferedReader(fr); 
    String line; 
    int nextBatch=0; 
    int i=0; 
    while((line=bfr.readLine())!= null) { 
     if (lineIncr <=nextBatch) { 
      System.out.println(line); 
      int b=0; 
      i=i+1; 
      if (i==2) { 
       b=b+1; 
       System.out.println("batchSize : "+b); 
System.out.println("batchSize : "+b); 
      } 
     } 

    } 
    bfr.close(); 
} 
} 

回答

2

试试这个:

final int batchSize = 2; 
Path file = Paths.get("C:\\Users\\me\\Desktop\\Files.txt"); 

try (BufferedReader bfr = Files.newBufferedReader(file)) { 
    List<String> batch = new ArrayList<>(batchSize); 
    for (String line; (line = bfr.readLine()) != null;) { 
     batch.add(line); 
     if (batch.size() == batchSize) { 
      process(batch); 
      batch = new ArrayList<>(batchSize); // or: batch.clear() 
     } 
    } 
    if (! batch.isEmpty()) { 
     process(batch); 
    } 
} 

显着特点:

  • 采用新NIO 2Path API,而不是老File API。

  • 用途try-with-resources确保Reader始终关闭正确。

  • 收集List<String>中的一批生产线。

  • 请致电process(List<String> batch)方法做处理。

  • 如果最后一批不完整,请拨打process()加上部分批次。

+0

感谢您分享。我将处理超过400万行文件。会不会有任何性能影响。我只是想明白......因为我可能需要给我10000批量。只是想知道。另外我如何从一条线恢复如果有任何问题或如何跳过行的情况下发生..从10001行向前读取 – Karthi

+0

添加'if(linesToSkip> 0){linesToSkip--; } for循环中的其他{...}。 – Andreas