开发者

Read a text file and create a 'Page' every 7 lines

How may I accomplish the task above? What I have been trying to do is separate the pages into different arrays but failed terribly.

Code by request (does not even close to work)

    int a = 1; int b = 5;
    File folder = new File("c:/files");
    File[] listOfFiles = folder.li开发者_JS百科stFiles();
    String[] page1 = new String[7];
    String[] page2 = new String[7];
    String[] page3 = new String[7];
    String[] page4 = new String[7];
    String[] page5 = new String[7];
    String[] page6 = new String[7];
    int c = 0;
    for (int i = 0;i<listOfFiles.length; i++)
    {
        if(i>=0 && i <= 7)
        {
            page1[i] = listOfFiles[i].getName();
        }
        else if(i>=8 && i<=15)
        {
            page2[i] = listOfFiles[i].getName();
        }
        else if(i>=16 && i<=23)
        {
            page3[i] = listOfFiles[i].getName();
        }
        else if(i>=24 && i<=31)
        {
            page4[i] = listOfFiles[i].getName();
        }
        else if(i>=32 && i<=39)
        {
            page5[i] = listOfFiles[i].getName();
        }
    }


This might help you:

  • Read text file in java
  • Use the modulo operator


Your code can't work, because when you do page2[i] = xxx, the variable named i should take a value between 0 and 6, and its value goes from 8 to 15. The same for the other pages. Even page1 will fail because the last index you use is 7, that is not in the range 0-6.

Try something like:

for (int i=0; i<listOfFiles.length; i++)
{
    if(i>=0 && i<7)
    {
        page1[i] = listOfFiles[i].getName();
    }
    else if(i>=7 && i<15)
    {
        page2[i-7] = listOfFiles[i].getName();
    }
    else if(i>=16 && i<23)
    {
        page3[i-16] = listOfFiles[i].getName();
    }
    ...
}

I hope you get the idea. Even this way your code is a little ugly to maintain, you should think about how to define only one bidimensional array, and to use the modulus (%) operator to access it in a simpler way and with less code.

The following code is untested, but I hope it guides you:

int NUM_PAGES = 7;
File folder = new File("c:/files");
File[] listOfFiles = folder.listFiles();

String[][] pages = new String[NUM_PAGES][listOfFiles.length/NUMPAGES];
for (int i=0; i<listOfFiles.length; i++) {
    int currentPage = i % 7;
    int currentPosition = pages[currentPage].length;
    pages[currentPage][currentPosition] = listOfFiles[i].getName();
}

You can also use Java Collections that would simplify your code even more;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜