首页 > 解决方案 > 在缓冲区阅读器 Java 中添加行计数器

问题描述

我被赋予了一项任务,我应该使用缓冲阅读器来读取文件,并计算文件中的行数。这样做之后,我应该拆分并解析它。有人可以帮忙吗?

package javaapplication12;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;



public class JavaApplication12 {


    public static void main(String[] args) {

        String count= "F:\\Gephi\\number.txt";

                BufferedReader br = null;
        FileReader fr = null;

        try {


            fr = new FileReader(count);
            br = new BufferedReader(fr);


            String sCurrentLine;

            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
            }


                    }    

                catch (IOException e) {

            e.printStackTrace();

                        }

在这里的某个地方,我想应该有一个代码读取文件中的行数,最后 {

            try {

                if (br != null)
                    br.close();

                if (fr != null)
                    fr.close();

            } 

                        catch (IOException ex) {

                ex.printStackTrace();

            }


                        if (count != null);

这里应该是拆分部分

                        String[] temp = count.split("/t");

拆分后应该有一个for循环并使用一个数组,它应该被解析

}




    }

}

标签: javabufferedreader

解决方案


阅读您的代码非常困难。请下次格式化。

我创建了一个名为“random_file.txt”的文件。其内容如下:

这是第 1 行...

这是第 2 行

这是另一条线...

还有一个

还有一个

现在我们可以用文件做所有你需要的事情。我们可以计算行数,打印每一行或解析它们。由于您没有准确指定要解析的内容,因此我编写了一个示例方法,该方法仅计算文件中的特定单词。应该使用正则表达式(正则表达式)进行解析。这是一个很好的链接: http ://www.vogella.com/tutorials/JavaRegularExpressions/article.html

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileParser
{
    private String filepath;

    public FileParser(String inputFilePath)
    {
        this.filepath = inputFilePath;
    }

    /**
     * Counts the number of lines.
     * 
     * @return Number of lines.
     * 
     * @throws FileNotFoundException If the file doesn't exist.
     * @throws IOException When an IO error occures.
     */
    public int countLines() throws FileNotFoundException, IOException
    {
        File file = new File(filepath);

        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);

        int counter = 0;
        while (br.readLine() != null)
        {
            counter++;
        }

        return counter;
    }

    /**
     * Splits the lines of the file and returns a list.
     * Each element of the list represents one line.
     * Note that the line seperator is excluded.
     * 
     * @throws FileNotFoundException If the file doesn't exist.
     * @throws IOException When an IO error occures.
     */
    public List<String> splitLines1() throws FileNotFoundException, IOException
    {
        File file = new File(filepath);

        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);

        String line;
        ArrayList<String> outputList = new ArrayList<>();
        while ((line = br.readLine()) != null)
        {
            outputList.add(line);
        }

        if (br != null) br.close();
        return outputList;
    }

    /**
     * Splits the lines of the file and returns a String.
     * Same as before, but now we have the line seperators included.
     * 
     * @throws FileNotFoundException If the file doesn't exist.
     * @throws IOException When an IO error occures.
     */
    public String splitLines2() throws FileNotFoundException, IOException
    {
        File file = new File(filepath);

        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);

        String line;
        StringBuilder builder = new StringBuilder();

        while ((line = br.readLine()) != null)
        {
            // we append every line to the builder
            // note that we get one line seperator more than
            // necessary (the one in the end)
            builder.append(line + System.lineSeparator());
        }

        if (br != null) br.close();
        return builder.toString();
    }

    /**
     * An example method for parsing. In this method we count the
     * number of times a word occures in given file.
     * 
     * @param word The word we are looking for.
     * 
     * @return Count the word occurencies.
     * 
     * @throws FileNotFoundException If the file doesn't exist.
     * @throws IOException When an IO error occures.
     */
    public int countOccurencies(String word)
            throws FileNotFoundException, IOException
    {
        List<String> fileLines = splitLines1(); // get the list, where each element represents one line
        int counter = 0;
        for (String line : fileLines)
        {
            // we split each line into words by splitting
            // at the spaces
            String[] words = line.split(" ");
            for (int i = 0; i < words.length; i++)
            {
                if (words[i].equals(word)) counter++;
            }
        }

        return counter;
    }

    /**
     * Testing the methods.
     */
    public static void main(String[] args) throws Exception
    {
        // Location of my file is in the project folder
        String filePath = System.getProperty("user.dir") + File.separator
                + "random_file.txt";
        FileParser fp = new FileParser(filePath);

        System.out.println("The file has " + fp.countLines() + " lines."
                + System.lineSeparator());

        System.out.println("We print a list holding each line as an element:");
        System.out.println(fp.splitLines1()
            .toString() + System.lineSeparator());

        System.out
            .println("Now we print the file contents as a single string:");
        System.out.println(fp.splitLines2());

        System.out
            .println("Now we count the occurencies of the word \"line\":");
        System.out.println(fp.countOccurencies("line"));
    }
}

这是控制台输出:

The file has 5 lines.

We print a list holding each line as an element:
[This is line 1 ..., And this is line number 2, This is another line ..., And one more, And another one]

Now we print the file contents as a single string:
This is line 1 ...
And this is line number 2
This is another line ...
And one more
And another one

Now we count the occurencies of the word "line":
3

推荐阅读