Java: How to count the no. of lines in a file?
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
Number of lines in a file in Java
我需要计算通过命令行参数传递给java的txt文件的行数。 我知道如何从文件中读取,但我在完成剩下的工作时遇到了麻烦。 任何帮助,将不胜感激。
这是我到目前为止:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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); } } |
为什么要在循环中拉
1 2 3 4 | while (file.hasNextLine()) { count++; file.nextLine(); } |
您应该检查java.util.Scanner类的javadoc:http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html
Scanner具有可用于此的方法hasNextLine和nextLine。 hasNextLine()检查文件中是否还有行,nextLine()从文件中读取一行。使用这些方法,您将获得如下算法:
1 2 3 4 | 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 |
你的代码可能是这样的
1 2 3 4 5 6 | int count = 0; while(file.hasNextLine()) { count++; file.nextLine() } |
你可以这样做:
1 2 3 4 5 6 7 | FileInputStream fstream = new FileInputStream("filename"); BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); String strLine; int count = 0; while ((strLine = br.readLine()) != null) { count++; } |
不久前我写了一个小项目分析器。这不是一个真正的答案,但我想分享我的解决方案。还没有
1 2 | MainFrame mf = new MainFrame(); mf.setVisible(true); |
它支持过滤文件扩展名上的文件。所以你可以指定例如C ++。这将接受所有
您必须指定一个文件夹,它将递归计算文件,行和字节。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 | 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 +" "; txt +="Lines:" + _lines +" "; txt +="Bytes:" + _bytes +" "; 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) { } } } } |
1 2 3 4 5 6 7 8 9 10 | BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(filename)); long count = 0; while ((line = reader.readLine()) != null) { count++; } } catch (Exception e) { // do something } |
您可以使用