分别检测第一行文本文件?

时间:2015-04-30 06:33:41

标签: java

我正在设计一个程序,将文本文件加载到不同的媒体文件类(Media> Audio> mp3,Media> Video> Avi等)。 现在,我的文本文件的第一行是总共有多少个文件,如

    3
    exmaple.mp3,fawg,gseges
    test.gif,wfwa,rgeg 
    ayylmao.avi,awf,gesg

现在这就是我的文本文件中的内容,我想先分别获取第一行,然后遍历其余文件。 现在我明白我可以通过使用一个随着循环而增长的int来计算有多少文件,但是我希望它在文件中清楚,并且我不确定如何去做。

static public Media[] importMedia(String fileName)
    {
        try {
            BufferedReader reader = new BufferedReader(new FileReader(fileName));
            String line = reader.readLine();
            while(line != null)
            {
                //Get the first line of the text file seperatly? (Then maybe remove it? idk)
                //Split string, create a temp media file and add it to a list for the rest of the lines
            }
            //String[] split = s.next().split(",");
        } catch (Exception ex) { System.out.println(ex.getMessage()); }
        return null;
    }

我希望我的问题很明确,如果 TL; DR 我想分别获取文本文件的第一行,那么其余的Id就要循环。

2 个答案:

答案 0 :(得分:3)

我不建议在这里使用for循环,因为该文件可能包含其他行(例如注释或空行)以使其更易于阅读。通过检查每一行的内容,您可以使您的处理更加强大。

static public Media[] importMedia(String fileName)
{
    try {
        BufferedReader reader = new BufferedReader(new FileReader(fileName));
        // Get and process first line:
        String line = reader.readLine(); // <-- Get the first line. You could consider reader as a queue (sort-of), where readLine() dequeues the first element in the reader queue.
        int numberOfItems = Integer.valueOf(line); // <-- Create an int of that line.
        // Do the rest:
        while((line = reader.readLine()) != null) // <-- Each call to reader.readLine() will get the next line in the buffer, so the first time around this will give you the second line, etc. until there are no lines left to read.
        {
             // You will not get the header here, only the rest.
             if(!line.isEmpty() || line.startsWith("#") {
                 // If the line is not empty and doesn't start with a comment character (I chose # here).
                 String[] split = line.split(",");
                 String fileName = split[0];
                 // etc...
             }
        }
    } catch (Exception ex) { System.out.println(ex.getMessage()); }
    return null;
}

答案 1 :(得分:1)

您不需要while循环来读取文件结尾。读取第一行并将其转换为int而不是循环。

static public Media[] importMedia(String fileName)
{
    try {

        BufferedReader reader = new BufferedReader(new FileReader(fileName));

        // Get and process first line:
        int lineNo=Integer.parseInt(reader.readLine());

        // Now read upto lineNo            
        for(int i=0; i < lineNo; i++){

            //Do what you need with other lines. 
            String[] values = reader.readLine().split(",");
        }

    } catch (Exception e) {
      //Your exception handling goes here
    }
}