【问题标题】:To add line counter in Buffer reader Java在缓冲区阅读器 Java 中添加行计数器
【发布时间】:2018-12-06 14:42:23
【问题描述】:

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

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循环并使用一个数组,它应该被解析

}




    }

}

【问题讨论】:

  • 嗯,JDK 中已经有 LineNumberReader:docs.oracle.com/javase/7/docs/api/java/io/LineNumberReader.html
  • 您需要更好地表达您的问题。真的很难理解你到底想要做什么。请更具体。另外,请尝试将 cmets 添加到您的代码示例中,就像您在实际代码中一样,使用 // 表示法。这样,应该放在一起的代码行是可见的。另外,我不确定“计数”到底应该是什么。它看起来像它的文件路径,但最后它看起来像它的内容。但同时从您的问题来看,听起来应该有一个行数。

标签: java bufferedreader


【解决方案1】:

你可以使用BufferedReader中的lines方法得到一个Stream的行,分割每一行,收集到一个List

List<String[]> lines;
try(BufferedReader reader = new BufferedReader(new FileReader("path"))) {
    lines = reader.lines()
        .map(line -> line.split("\t"))
        .collect(Collectors.toList());
}

【讨论】:

    【解决方案2】:

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

    我创建了一个名为“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
    

    【讨论】:

    • 非常感谢您的帮助,实际上,我是堆栈溢出的新手,请原谅我的任何错误,我会记住并尝试下次正确发布.! TQ
    • 没问题,希望对您有所帮助。
    猜你喜欢
    • 2015-02-06
    • 2016-06-17
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 2012-07-02
    • 2019-07-08
    • 1970-01-01
    • 2020-06-30
    相关资源
    最近更新 更多