Split file into multiple files

后端 未结 1 915
无人共我
无人共我 2021-01-28 03:57

I want to cut a text file. I want to cut the file 50 lines by 50 lines.

For example, If the file is 1010 lines, I would recover 21 files.

I know how to count the

相关标签:
1条回答
  • 2021-01-28 04:05

    you count the lines first

    while((line = br.readLine()) != null){
                        sourcesize++; }
    

    and then you're at the end of the file: you read nothing

    for (int i=1;i<=numSplits;i++)  {  
                    while((line = br.readLine()) != null){
    

    You have to seek back to the start of the file before reading again.

    But that's a waste of time & power because you'll read the file twice

    It's better to read the file once and for all, put it in a List<String> (resizable), and proceed with your split using the lines stored in memory.

    EDIT: seems that you followed my advice and stumbled on the next issue. You should have maybe asked another question, well... this creates a buffer with all the lines.

    for (String value : list) {
                    builder.append("/n"+value);
                }
    

    You have to use indexes on the list to build small files.

    for (int k=0;k<numSplits;k++) {  
          builder.append("/n"+list[current_line++]);
    

    current_line being the global line counter in your file. That way you create files of 50 different lines each time :)

    0 讨论(0)
提交回复
热议问题