我需要计算通过命令行参数传递给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);
}
}
答案 0 :(得分:8)
为什么要在循环中拉nextInt()
并保存hasNext()
?如果你在那里,你已经知道另一条线存在,那么为什么不这样做:
while (file.hasNextLine()) {
count++;
file.nextLine();
}
答案 1 :(得分:4)
您应该检查java.util.Scanner类的javadoc:http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html
Scanner具有可用于此的方法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()
}
答案 2 :(得分:3)
你可以这样做:
FileInputStream fstream = new FileInputStream("filename");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
int count = 0;
while ((strLine = br.readLine()) != null) {
count++;
}
答案 3 :(得分:1)
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(filename));
long count = 0;
while ((line = reader.readLine()) != null) {
count++;
}
} catch (Exception e) {
// do something
}
答案 4 :(得分:1)
前段时间我写了一个小项目分析器。这不是一个真正的答案,但我想分享我的解决方案。还没有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)
{
}
}
}
}
答案 5 :(得分:0)
您可以使用BufferedReader
来读取完整的行或LineNumberReader
进行计数本身。