Java:如何计算数量。文件中的行数?

发布于 2024-12-06 00:33:22 字数 655 浏览 0 评论 0原文

可能的重复:
Java 文件中的行数

我需要计算通过命令行参数传递给 java 的 txt 文件的行数。我知道如何从文件中读取内容,但我在完成其余的事情时遇到了困难。任何帮助将不胜感激。 这是我到目前为止所拥有的:

   import java.util.*;
   import java.io.*;
   public class LineCounter {
public static void main (String [] args) throws IOException{
    Scanner file = new Scanner(new File("myFlile.txt"));
    int count = 0;
    while(file.hasNext()){
        boolean s = file.hasNext();
        int count = file.nextInt();
    }

    System.out.println(count);
   }
     }

Possible Duplicate:
Number of lines in a file in Java

I need to count the number of lines of a txt file that is passed to java through a command line argument. I know how to read from a file but i am having trouble doing the rest. any help would be appreciated.
here is what i have so far:

   import java.util.*;
   import java.io.*;
   public class LineCounter {
public static void main (String [] args) throws IOException{
    Scanner file = new Scanner(new File("myFlile.txt"));
    int count = 0;
    while(file.hasNext()){
        boolean s = file.hasNext();
        int count = file.nextInt();
    }

    System.out.println(count);
   }
     }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

熟人话多 2024-12-13 00:33:22

为什么要在循环内拉动 nextInt() 并保存 hasNext() ?如果您在那里,您已经知道存在另一条线,那么为什么不执行以下操作:

while (file.hasNextLine()) {
  count++;
  file.nextLine();
}

Why are you pulling nextInt() and saving hasNext() inside the loop? If you are in there, you already know another line exists, so why not do something like:

while (file.hasNextLine()) {
  count++;
  file.nextLine();
}
甜柠檬 2024-12-13 00:33:22

您应该检查 javadoc 中的 java.util.Scanner 类: http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html

扫描程序具有可用于此目的的方法 hasNextLine 和 nextLine。 hasNextLine() 检查文件中是否还有行,nextLine() 从文件中读取一行。使用这些方法,你会得到这样的算法:

let the amount of lines be 0
as long as there are lines left in file
    read one line and go to the next line
    increment amount of lines by 1

你的代码可能是这样的

int count = 0;
while(file.hasNextLine())
{
    count++;
    file.nextLine()
}

You should check javadoc for the java.util.Scanner class: http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html

Scanner has methods hasNextLine and nextLine that you can use for this. hasNextLine() checks if there are still lines in the files and nextLine() reads one line from the file. Using those methods you get an algorithm like this:

let the amount of lines be 0
as long as there are lines left in file
    read one line and go to the next line
    increment amount of lines by 1

Your code could be something like this

int count = 0;
while(file.hasNextLine())
{
    count++;
    file.nextLine()
}
清风不识月 2024-12-13 00:33:22

你可以这样做:

FileInputStream fstream = new FileInputStream("filename");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
int count = 0;
while ((strLine = br.readLine()) != null)   {
  count++;
}

You can do it this way:

FileInputStream fstream = new FileInputStream("filename");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
int count = 0;
while ((strLine = br.readLine()) != null)   {
  count++;
}
风为裳 2024-12-13 00:33:22
    BufferedReader reader = null;
    try { 
        reader = new BufferedReader(new FileReader(filename));
        long count = 0;
        while ((line = reader.readLine()) != null) {
            count++;
        }
    } catch (Exception e) {
         // do something
    }
    BufferedReader reader = null;
    try { 
        reader = new BufferedReader(new FileReader(filename));
        long count = 0;
        while ((line = reader.readLine()) != null) {
            count++;
        }
    } catch (Exception e) {
         // do something
    }
浅笑轻吟梦一曲 2024-12-13 00:33:22

不久前,我写了一个小型项目分析器。这并不是一个真正的答案,但我想分享我的解决方案。目前还没有 main() 方法。只需创建一个这样的:

MainFrame mf = new MainFrame();
mf.setVisible(true);

它支持根据文件扩展名过滤文件。因此您可以指定例如 C++。这将接受所有 .h.cpp 文件。

您必须指定一个文件夹,它将递归地计算文件、行和字节数。

import java.awt.event.ItemEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 *
 * @author martijncourteaux
 */
public class MainFrame extends javax.swing.JFrame
{

    private File root;
    private volatile int _files;
    private volatile int _lines;
    private volatile long _bytes;

    /** Creates new form MainFrame */
    public MainFrame()
    {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        btnSelectRoot = new javax.swing.JButton();
        lblRoot = new javax.swing.JLabel();
        cmbExtensions = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        btnAnalyse = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Project Analyser");
        setLocation(new java.awt.Point(40, 62));

        jLabel1.setText("Project Root:");

        btnSelectRoot.setText("Select");
        btnSelectRoot.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSelectRootActionPerformed(evt);
            }
        });

        lblRoot.setText(" ");

        cmbExtensions.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "[Any]", "h;cpp", "java", "xml", "Customize..." }));
        cmbExtensions.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cmbExtensionsItemStateChanged(evt);
            }
        });

        jLabel2.setText("Extensions:");

        btnAnalyse.setText("Analyse");
        btnAnalyse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAnalyseActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(cmbExtensions, 0, 352, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(jLabel1)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(lblRoot, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 174, Short.MAX_VALUE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(btnSelectRoot))
                    .add(jLabel2)
                    .add(btnAnalyse, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 352, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel1)
                    .add(btnSelectRoot)
                    .add(lblRoot))
                .add(18, 18, 18)
                .add(jLabel2)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(cmbExtensions, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(btnAnalyse, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 90, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSelectRootActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnSelectRootActionPerformed
    {//GEN-HEADEREND:event_btnSelectRootActionPerformed
        JFileChooser fc = new JFileChooser(root.getParentFile());
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int option = fc.showDialog(this, "Select");
        if (option == JFileChooser.APPROVE_OPTION)
        {
            this.root = fc.getSelectedFile();
            this.lblRoot.setText(root.getParentFile().getName() + "/" + root.getName());
        }
    }//GEN-LAST:event_btnSelectRootActionPerformed

    private void cmbExtensionsItemStateChanged(java.awt.event.ItemEvent evt)//GEN-FIRST:event_cmbExtensionsItemStateChanged
    {//GEN-HEADEREND:event_cmbExtensionsItemStateChanged
        if (cmbExtensions.getSelectedIndex() == cmbExtensions.getItemCount() - 1 && evt.getStateChange() == ItemEvent.SELECTED)
        {
            evt.getStateChange();
            String extensions = JOptionPane.showInputDialog(this, "Specify the extensions, seperated by semi-colon (;) and without dot.");
            if (extensions == null)
            {
                cmbExtensions.setSelectedIndex(0);
                return;
            }
            DefaultComboBoxModel model = (DefaultComboBoxModel) cmbExtensions.getModel();
            model.insertElementAt(extensions, cmbExtensions.getSelectedIndex());
            cmbExtensions.validate();
            cmbExtensions.setSelectedIndex(cmbExtensions.getItemCount() - 2);
        }
    }//GEN-LAST:event_cmbExtensionsItemStateChanged

    private void btnAnalyseActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnAnalyseActionPerformed
    {//GEN-HEADEREND:event_btnAnalyseActionPerformed
        if (root == null)
        {
            JOptionPane.showMessageDialog(this, "Please select a root.");
            return;
        }
        _files = 0;
        _lines = 0;
        _bytes = 0L;
        btnAnalyse.setHorizontalAlignment(JButton.LEFT);
        updateButtonText();
        final int i = cmbExtensions.getSelectedIndex();
        final String[] extensions = cmbExtensions.getSelectedItem().toString().toLowerCase().split(";");
        final FileFilter ff = new FileFilter()
        {

            @Override
            public boolean accept(File file)
            {
                if (i == 0) return true;
                if (file.isDirectory())
                {
                    return true;
                }
                String name = file.getName().toLowerCase();

                for (String ext : extensions)
                {
                    if (name.endsWith(ext))
                    {
                        return true;
                    }
                }
                return false;
            }
        };

        final SwingWorker<Void, Void> sw = new SwingWorker<Void, Void>()
        {

            @Override
            protected Void doInBackground() throws Exception
            {
                scan(root, ff);
                updateButtonText();
                return null;
            }
        };
        sw.execute();
        final SwingWorker<Void, Void> sw2 = new SwingWorker<Void, Void>()
        {

            @Override
            protected Void doInBackground() throws Exception
            {
                while (!sw.isDone())
                {
                    updateButtonText();
                }
                return null;
            }
        };
        sw2.execute();
    }//GEN-LAST:event_btnAnalyseActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAnalyse;
    private javax.swing.JButton btnSelectRoot;
    private javax.swing.JComboBox cmbExtensions;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel lblRoot;
    // End of variables declaration//GEN-END:variables

    private void updateButtonText()
    {
        String txt = "<html>";
        txt += "Files: " + _files + "<br>\n";
        txt += "Lines: " + _lines + "<br>\n";
        txt += "Bytes: " + _bytes + "\n";
        btnAnalyse.setText(txt);
    }

    private void scan(File folder, FileFilter ff)
    {
        File[] files = folder.listFiles(ff);
        try
        {
            for (File f : files)
            {
                if (f == null)
                {
                    continue;
                }
                if (f.isDirectory())
                {
                    scan(f, ff);
                } else
                {
                    analyse(f);
                }
            }
        } catch (Exception e)
        {
        }
    }

    private void analyse(File f)
    {
        if (f.exists())
        {
            _files++;
            _bytes += f.length();

            try
            {
                BufferedReader r = new BufferedReader(new FileReader(f));
                while (r.readLine() != null)
                {
                    _lines++;
                }
                r.close();
            } catch (Exception e)
            {
            }
        }
    }
}

I wrote a little project analyser, some time ago. It's not really an answer, but I wanted to share my solution. There is no main() method yet. Just create one like this:

MainFrame mf = new MainFrame();
mf.setVisible(true);

It supports for filtering files on file extensions. So you can specify for example C++. This will accept all .h and .cpp files.

You have to specify a folder and it will recursively count files, lines and bytes.

import java.awt.event.ItemEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 *
 * @author martijncourteaux
 */
public class MainFrame extends javax.swing.JFrame
{

    private File root;
    private volatile int _files;
    private volatile int _lines;
    private volatile long _bytes;

    /** Creates new form MainFrame */
    public MainFrame()
    {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        btnSelectRoot = new javax.swing.JButton();
        lblRoot = new javax.swing.JLabel();
        cmbExtensions = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        btnAnalyse = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Project Analyser");
        setLocation(new java.awt.Point(40, 62));

        jLabel1.setText("Project Root:");

        btnSelectRoot.setText("Select");
        btnSelectRoot.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSelectRootActionPerformed(evt);
            }
        });

        lblRoot.setText(" ");

        cmbExtensions.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "[Any]", "h;cpp", "java", "xml", "Customize..." }));
        cmbExtensions.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cmbExtensionsItemStateChanged(evt);
            }
        });

        jLabel2.setText("Extensions:");

        btnAnalyse.setText("Analyse");
        btnAnalyse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAnalyseActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(cmbExtensions, 0, 352, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(jLabel1)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(lblRoot, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 174, Short.MAX_VALUE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(btnSelectRoot))
                    .add(jLabel2)
                    .add(btnAnalyse, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 352, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel1)
                    .add(btnSelectRoot)
                    .add(lblRoot))
                .add(18, 18, 18)
                .add(jLabel2)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(cmbExtensions, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(btnAnalyse, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 90, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSelectRootActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnSelectRootActionPerformed
    {//GEN-HEADEREND:event_btnSelectRootActionPerformed
        JFileChooser fc = new JFileChooser(root.getParentFile());
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int option = fc.showDialog(this, "Select");
        if (option == JFileChooser.APPROVE_OPTION)
        {
            this.root = fc.getSelectedFile();
            this.lblRoot.setText(root.getParentFile().getName() + "/" + root.getName());
        }
    }//GEN-LAST:event_btnSelectRootActionPerformed

    private void cmbExtensionsItemStateChanged(java.awt.event.ItemEvent evt)//GEN-FIRST:event_cmbExtensionsItemStateChanged
    {//GEN-HEADEREND:event_cmbExtensionsItemStateChanged
        if (cmbExtensions.getSelectedIndex() == cmbExtensions.getItemCount() - 1 && evt.getStateChange() == ItemEvent.SELECTED)
        {
            evt.getStateChange();
            String extensions = JOptionPane.showInputDialog(this, "Specify the extensions, seperated by semi-colon (;) and without dot.");
            if (extensions == null)
            {
                cmbExtensions.setSelectedIndex(0);
                return;
            }
            DefaultComboBoxModel model = (DefaultComboBoxModel) cmbExtensions.getModel();
            model.insertElementAt(extensions, cmbExtensions.getSelectedIndex());
            cmbExtensions.validate();
            cmbExtensions.setSelectedIndex(cmbExtensions.getItemCount() - 2);
        }
    }//GEN-LAST:event_cmbExtensionsItemStateChanged

    private void btnAnalyseActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnAnalyseActionPerformed
    {//GEN-HEADEREND:event_btnAnalyseActionPerformed
        if (root == null)
        {
            JOptionPane.showMessageDialog(this, "Please select a root.");
            return;
        }
        _files = 0;
        _lines = 0;
        _bytes = 0L;
        btnAnalyse.setHorizontalAlignment(JButton.LEFT);
        updateButtonText();
        final int i = cmbExtensions.getSelectedIndex();
        final String[] extensions = cmbExtensions.getSelectedItem().toString().toLowerCase().split(";");
        final FileFilter ff = new FileFilter()
        {

            @Override
            public boolean accept(File file)
            {
                if (i == 0) return true;
                if (file.isDirectory())
                {
                    return true;
                }
                String name = file.getName().toLowerCase();

                for (String ext : extensions)
                {
                    if (name.endsWith(ext))
                    {
                        return true;
                    }
                }
                return false;
            }
        };

        final SwingWorker<Void, Void> sw = new SwingWorker<Void, Void>()
        {

            @Override
            protected Void doInBackground() throws Exception
            {
                scan(root, ff);
                updateButtonText();
                return null;
            }
        };
        sw.execute();
        final SwingWorker<Void, Void> sw2 = new SwingWorker<Void, Void>()
        {

            @Override
            protected Void doInBackground() throws Exception
            {
                while (!sw.isDone())
                {
                    updateButtonText();
                }
                return null;
            }
        };
        sw2.execute();
    }//GEN-LAST:event_btnAnalyseActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAnalyse;
    private javax.swing.JButton btnSelectRoot;
    private javax.swing.JComboBox cmbExtensions;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel lblRoot;
    // End of variables declaration//GEN-END:variables

    private void updateButtonText()
    {
        String txt = "<html>";
        txt += "Files: " + _files + "<br>\n";
        txt += "Lines: " + _lines + "<br>\n";
        txt += "Bytes: " + _bytes + "\n";
        btnAnalyse.setText(txt);
    }

    private void scan(File folder, FileFilter ff)
    {
        File[] files = folder.listFiles(ff);
        try
        {
            for (File f : files)
            {
                if (f == null)
                {
                    continue;
                }
                if (f.isDirectory())
                {
                    scan(f, ff);
                } else
                {
                    analyse(f);
                }
            }
        } catch (Exception e)
        {
        }
    }

    private void analyse(File f)
    {
        if (f.exists())
        {
            _files++;
            _bytes += f.length();

            try
            {
                BufferedReader r = new BufferedReader(new FileReader(f));
                while (r.readLine() != null)
                {
                    _lines++;
                }
                r.close();
            } catch (Exception e)
            {
            }
        }
    }
}
蓝天 2024-12-13 00:33:22

您可以使用 BufferedReader< /a> 读取完整行或 LineNumberReader 本身进行计数。

You can use a BufferedReader to read complete lines or a LineNumberReader which does the counting itself.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文