将文件拆分为多个文件
我想剪切一个文本文件。 我想将文件50行剪切50行。
例如,如果文件是1010行,我将恢复21个文件。
我知道如何计算文件的数量,行数,但是一旦我写,它就不起作用。
我使用Camel Simple(Talend),但它是Java代码。
private void ExtractOrderFromBAC02(ProducerTemplate producerTemplate, InputStream content, String endpoint, String fileName, HashMap headers){ ArrayList list = new ArrayList(); BufferedReader br = new BufferedReader(new InputStreamReader(content)); String line; long numSplits = 50; int sourcesize=0; int nof=0; int number = 800; try { while((line = br.readLine()) != null){ sourcesize++; list.add(line); } System.out.println("Lines in the file: " + sourcesize); double numberFiles = (sourcesize/numSplits); int numberFiles1=(int)numberFiles; if(sourcesize<=50) { nof=1; } else { nof=numberFiles1+1; } System.out.println("No. of files to be generated :"+nof); for (int j=1;j<=nof;j++) { number++; String Filename = ""+ number; System.out.println(Filename); StringBuilder builder = new StringBuilder(); for (String value : list) { builder.append("/n"+value); } producerTemplate.sendBodyAndHeader(endpoint, builder.toString(), "CamelFileName",Filename); } } } catch (IOException e) { e.printStackTrace(); } finally{ try { if(br != null)br.close(); } catch (IOException e) { e.printStackTrace(); } } } }
对于不了解Camel的人,此行用于发送文件:
producerTemplate.sendBodyAndHeader (endpoint, line.toString (), "CamelFileName" Filename);
endpoint ==> Destination(可以使用其他代码)
line.toString()==>值
然后是文件名(可以使用其他代码)
你先计算一下这些线
while((line = br.readLine()) != null){ sourcesize++; }
然后你就在文件的最后:你什么也没读
for (int i=1;i<=numSplits;i++) { while((line = br.readLine()) != null){
在重新阅读之前,您必须回到文件的开头。
但这是浪费时间和力量,因为你会读两次文件
最好一次性读取文件,将其放入List
(可resize),然后使用存储在内存中的行继续进行拆分。
编辑:似乎你按照我的建议,偶然发现了下一期。 你可能会问另一个问题,好吧......这会创建一个包含所有行的缓冲区。
for (String value : list) { builder.append("/n"+value); }
您必须使用列表上的索引来构建小文件。
for (int k=0;k
current_line
是文件中的全局行计数器。 这样你每次创建50个不同行的文件:)