Number of lines in a file in Java

前端 未结 19 2346
抹茶落季
抹茶落季 2020-11-22 05:31

I use huge data files, sometimes I only need to know the number of lines in these files, usually I open them up and read them line by line until I reach the end of the file<

19条回答
  •  逝去的感伤
    2020-11-22 06:05

    Best Optimized code for multi line files having no newline('\n') character at EOF.

    /**
     * 
     * @param filename
     * @return
     * @throws IOException
     */
    public static int countLines(String filename) throws IOException {
        int count = 0;
        boolean empty = true;
        FileInputStream fis = null;
        InputStream is = null;
        try {
            fis = new FileInputStream(filename);
            is = new BufferedInputStream(fis);
            byte[] c = new byte[1024];
            int readChars = 0;
            boolean isLine = false;
            while ((readChars = is.read(c)) != -1) {
                empty = false;
                for (int i = 0; i < readChars; ++i) {
                    if ( c[i] == '\n' ) {
                        isLine = false;
                        ++count;
                    }else if(!isLine && c[i] != '\n' && c[i] != '\r'){   //Case to handle line count where no New Line character present at EOF
                        isLine = true;
                    }
                }
            }
            if(isLine){
                ++count;
            }
        }catch(IOException e){
            e.printStackTrace();
        }finally {
            if(is != null){
                is.close();    
            }
            if(fis != null){
                fis.close();    
            }
        }
        LOG.info("count: "+count);
        return (count == 0 && !empty) ? 1 : count;
    }
    

提交回复
热议问题