Counting Lines/Char/Words in a txt file

I created this method that counts the mount of lines/words/ and char in a file. But for somereason, its not working correctly. Its giving me numbers that are a little off.
     // Method countLineWordChar counts the number of lines, words, and chars, in
     // a file given as a parameter. This method returns an array of intergers. In
     // the array, the first position is the amount of lines, the second posistion
     // is the amount of words, and the third is the amount of chars.
     public static int[] countLineWordChar(File f)
          int[] countInfo = new int[3];
          int lineCount = 0;
          int wordCount = 0;
          int charCount = 0;
          try
               FileReader fr = new FileReader(f);
               StreamTokenizer st = new StreamTokenizer(fr);
               st.eolIsSignificant(true);
               while(st.nextToken() != StreamTokenizer.TT_EOF)
                    switch(st.ttype)
                         case StreamTokenizer.TT_WORD:
                         wordCount++;
                         String wordRead = st.sval;
                         charCount += wordRead.length();
                         break;
                         case StreamTokenizer.TT_EOL:
                         lineCount++;
                         break;
                         default:
                         break;
          catch (FileNotFoundException fnfe)
               UserInterface.showFileNotFoundError();
          catch (IOException ioe)
               JOptionPane.showMessageDialog(null, ioe.toString(), "Error",
               JOptionPane.ERROR_MESSAGE);
          countInfo[0] = lineCount;
          countInfo[1] = wordCount;
          countInfo[2] = charCount;
          return countInfo;
     // Based on the countLineWordChar method, returns the amount of lines.
     public static int getLineCount(int[] countInfo)
          return countInfo[0];
     // Based on the countLineWordChar method, returns the amount of words.
     public static int getWordCount(int[] countInfo)
          return countInfo[1];
     // Based on the countLineWordChar method, returns the amount of chars.
     public static int getCharCount(int[] countInfo)
          return countInfo[2];
     }

Well, for one thing, you're adding the number of characters in words, not the number of characters overall. Are you sure it's not supposed to be the latter?
Otherwise, how is it off?
Basically the way you fix this kind of thing is to add debugging code, then give it a small data sample and watch the debugging messages.
By the way, returning an array of different kinds of values like that isn't ideal. In this case it's not so bad, because the kinds of values are actually really similar -- they could be viewed as a tuple. But don't make a habit of it. An example of a bad application of this would be if you were returning an array that counted, say, the weight of a ship, the length of its hull, and the distance it travelled in the last year. The alternative is to create a class that encapsulates the data being returned, or to move functionality around so the data isn't being returned at all.

Similar Messages

  • I need autocomplete  for search for words in a txt. file

    i am not so good in java.
    I have a running code for search in text with a txt. file (from user bluefox815).
    But I need a solution with autocomplete for search for words in a txt. file.
    test_file.txt (Teil des Inhaltes):
    Roboter robots
    Mechatronik mechatronics
    and so on
    Can you help me please.
    Here is the code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    * this program searches for a string in a text file and
    * says which line it found the string on
    public class SearchText implements ActionListener {
    private String filename = "test_file.txt";
    private JFrame frame;
    private JTextField searchField;
    private JButton searchButton;
    private JLabel lineLabel;
    private String searchFor;
    private BufferedReader in;
    public SearchText() {
    frame = new JFrame("SearchText");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    searchField = new JTextField(80);
    searchButton = new JButton("Search");
    // this is used later in our actionPerformed method
    searchButton.setActionCommand("search");
    // this sets the action listener for searchButton, which is the current class
    // because this class implements ActionListener
    searchButton.addActionListener(this);
    lineLabel = new JLabel("nach dem Fachbegriff suchen");
    public void createGUI() {
    JPanel topPanel = new JPanel();
    topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.X_AXIS));
    JPanel bottomPanel = new JPanel();
    JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
    topPanel.add(searchField);
    topPanel.add(searchButton);
    bottomPanel.add(lineLabel);
    mainPanel.add(topPanel);
    mainPanel.add(bottomPanel);
    frame.getContentPane().add(mainPanel);
    frame.pack();
    frame.setVisible(true);
    public void actionPerformed(ActionEvent e) {
    // now we get the action command and if it is search, then it is the button
    if ("search".equals(e.getActionCommand())) {
    searchFor = searchField.getText();
    searchTheText();
    private void searchTheText() {
    // I initialize the buffered reader here so that every time the user searches
    // then the reader will start at the beginning, instead of where it left off last time
    try {
    in = new BufferedReader(new FileReader(new File(filename)));
    } catch (IOException e) {
    String lineContent = null;
    int currentLine = 0;
    // this will be set to true if the string was found
    boolean foundString = false;
    while (true) {
    currentLine++;
    // get a line of text from the file
    try {
    lineContent = in.readLine();
    } catch (IOException e) {
    break;
    // checks to see if the file ended (in.readLine() returns null if the end is reached)
    if (lineContent == null) {
    break;
    if (lineContent.indexOf(searchFor) == -1) {
    continue;
    } else {
    lineLabel.setText(String.valueOf(lineContent));
    foundString = true;
    break;
    if (!foundString)
    lineLabel.setText("Es kann kein Fachbegriff gefunden werden.");
    try {
    in.close();
    } catch (IOException ioe) {
    public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    new SearchText().createGUI();
    }

    Markus1 wrote:
    But I need a solution with autocomplete for search for words in a txt. file.What is your question? What have you tried so far? What are you having difficulty with?
    Mel

  • Finding words in a txt file!

    Hi guys,
    I have to write a program that opens a .txt file and looks for a specific word in the file and then prints out the entire line that word appears in. I have to use a String Tokenizer? I don't know how to write the program. All I have so far is a program that prints the entire txt document (or each line). I think String Tokenizer is involved in here somewhere but I don't know how to use it.
    import java.io.FileReader;
    import java.util.StringTokenizer;
    import java.io.*;
    public class Find
         public static void main (String[] args) throws IOException
              String line;
              String name;
              String file="find.txt";
              StringTokenizer tokenizer;
              FileReader x = new FileReader (file);
              BufferedReader inFile = new BufferedReader (x);
              line = inFile.readLine();
              while (line != null)
                   tokenizer = new StringTokenizer (line);
    word = tokenizer.nextToken("word");
                   System.out.println (line + "\n");
                   line = inFile.readLine();
              inFile.close();
    The text file Find.txt just has a few lines of text in it.
    I want to make it so that I can look for a specific word in the text file and the resulting printout will be the entire line that the word appears in.
    Any help would be great! Thanks!

    Your first post is very close to what you want:
    import java.io.FileReader;
    import java.util.StringTokenizer;
    import java.io.*;
    public class Find
         public static void main (String[] args) throws IOException
         String line;
         String name;
         String file="find.txt";
         StringTokenizer tokenizer;
         FileReader x = new FileReader (file);
         BufferedReader inFile = new BufferedReader (x);
         line = inFile.readLine();
         while (line != null)
              tokenizer = new StringTokenizer (line);
              String word = tokenizer.nextToken();
              if (word.equals("word")) // we are searchig for the String word
                   System.out.println ("found it! "+line + "\n");
              line = inFile.readLine();
         inFile.close();
    [\code]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • What is the 'quickest' way to read char data from a txt file

    Hello,
    What is the 'quickest' way to read character data from a txt file stored on the phone to be displayed into the screen?
    Regards

    To be even a bit more constructive...
    Since J2me does not have a BufferedInputStream, it will help to implement it yourself. It's much faster since you read large blocks at ones in stread of seperate chars.
    something line this lets you read lines very fast:
      while ( bytesread < filesize ) {
             length = configfile.read( buff, 0, buff.length );
             // append buffer to temp String
             if ( length < buff.length ) {
                byte[]  buf  = new byte[length];
                System.arraycopy( buff, 0, buf, 0, length );
                tmp.append( new String( buf ) );
             } else {
                tmp.append( new String( buff ) );
             // look in tmp string for \r\n
             idx1 = tmp.toString().indexOf( "\r\n" );
             while ( idx1 >= 0 ) {
                //if found, split into line and rest of tmp
                line = tmp.toString().substring( 0, idx1 );
             /// ... do with it whatever you want ... ////
                tmp = new StringBuffer( tmp.toString().substring( idx1 + 2 ) );
                idx1 = tmp.toString().indexOf( "\r\n" );
             bytesread += length;
          }

  • How to read Chinese word from a TXT file

    File.OpenText() read a TXT File with  Chinese word in   ;but it not show right.
    exam:The TXT File include :中国
     this.Txt1.Text=ofd.File.OpenText().ReadToEnd();
    but it show :��ʹ�ݼƻ��
    How to solve it

    What encoding does the text file use?  Unlike .NET, Silverlight only supports UTF-8 and UTF-16.  File.OpenText() uses UTF-8 by default.
    If the text file is in some other encoding, you can create your own encoding class (that derives from System.Text.Encoding) that can be used to read the text file.
    class MyEncoding : System.Text.Encoding {
    this.Txt1.Text = (new StreamReader(ofd.File.OpenRead(), new MyEncoding())).ReadToEnd();
    Regards,
    Justin Van Patten
    Program Manager
    Common Language Runtime

  • Tagging words through a .txt file

    Hi all,
    We have been looking all over the internet for a script that we can use/buy. But cannot find it anywhere.
    We have a rather large document and an external word list in a .txt file. This list contains words that need to be in the index at the end of the document.
    Instead of filling in a couple of hundred words and linking them by hand, it would be great if there is a script that can handle this.
    We have looked in to Indexmatic2 (http://www.indiscripts.com/post/2011/07/indexmatic-2-public-release-and-user-s-guide ), but this script generates its own index list and does not create links to the original words in the document.
    We have found a script that can create index links from colored words in the document.
    So does anyone know if there is a script floating around that can load an external .txt wordlist and either color or add a character style to words in a document?
    Or even a script that does what we need in 1 go?
    Thanks

    Thedesmodus,
    there is a script by Martin Fischer at www.hilfdirselbst.ch (a swizz-german website) that could fit your needs. You can download it if you choose to be a premium member which requires a small fee. It's written for InDesign CS3 but it should run with CS4 or CS5. I tested it with a small list of words and it ran fine with InDesign CS5.
    http://indesign.hilfdirselbst.ch/text/indexeintrage-mit-unterstichworten-uber-eine-konkord anzdatei-erzeugen.html
    If you prefer a Google translation:
    http://translate.google.de/translate?hl=de&sl=de&tl=en&u=http%3A%2F%2Findesign.hilfdirselb st.ch%2Ftext%2Findexeintrage-mit-unterstichworten-uber-eine-konkordanzdatei-erzeugen.html
    Uwe

  • How to insert new line char while writing bytes into file

    Hello Sir,
    Is it possible to insert the new line character in set of String variables and stored them into bytearray ,then finally write into File?
    This is the sample code which i tried:
                 File f = new File(messagesDir,"msg" + msgnum + ".txt");
                 FileOutputStream fout = new FileOutputStream(f);
                    String fromString = "From:    "+msg.getFrom()+"\n";
                    String toString = "To:     "+msg.getTo()+"\n";
                    String dateString = "Sent:    "+msg.getDate()+"\n";
                      String msgString =msg.getBody()+"\n";
                    String finalString=fromString+toString+dateString+msgString;
                    byte[] msgBytes = finalString.getBytes();
                    fout.write(msgBytes);
                 fout.close();in the above code , i tried to add the new line as "\n" in end of each string. but when i look into the generated files msg1.txt , it contains some junk char [] .
    please provide me the help
    regards
    venki

    but it has still shown the the junk char, its not able
    to create the new line in the created file i am afraid
    how am i going to get the solution?:(Do not be afraid dear sir. You are obviously using a windows operating system or a mac operating system. On windows a newline is "\r\n" not '\n', and on a mac a newline is '\r', not '\n'. If you make that correction, dear sir, your program will work.
    However, there is a better way. First, you probably want to buffer your output if you are going to write more than one time to the file, which will make writing to the file more efficient. In addition, when you buffer your output, you can use the newLine() method of the BufferedWriter object to insert a newline. The newline will be appropriate for the operating system that the program is running on. Here is an example:
    File f = new File("C:/TestData/atest.txt");
    BufferedWriter out = new BufferedWriter(new FileWriter(f) );
    String fromString = "From: Jane";
    out.write(fromString);
    //Not written to the file until enough data accumulates.
    //The data is stored in a buffer until then.
    out.newLine();
    String toString = "To: Dick";
    out.write(toString);
    out.newLine();
    String dateString = "Sent: October 27, 2006";
    out.write(dateString);
    out.newLine();
    out.close(); 
    //Causes any unwritten data to be flushed from
    //the buffer and written to the file.

  • Why would only the first line of my data set txt file work?

    Hi -
    I had a lot of success using variables and external data sets until today.
    I have an external text file that I have imported as a data set (Image/Variables/Data Sets/Import...).  All of the variables have been defined and confirmed (at least PSD hasn't told me it can't find something which is the typical error msg.)
    This external text file, with the extension ".txt" has 12 lines on it, each line is 7 comma separated values, and each line is ending in a carriage return.
    YESTERDAY when I used File/Export/Export Data Set as Files... the procedure went beautifully for the 8 times I used it.  TODAY I only get the first of the 12 lines completed and then the export stops.  There are no error messages or other signs that Photoshop has choked on something so I guess something is wrong with my text file... BUT WHAT??
    Any insight on any step in this would be helpful.  You all know that if I'm using this feature it's because I have TONS of repetition ahead of me if it doesn't work.
    TIA your expertise,
    JL

    Fixed it!
    When Exporting as Data sets as files... the step I missed was to select "All Data Sets" from the Data Set drop down.
    Thanks all.
    JL

  • Count from a .TXT file

    Hi Gurs...
    Plx help
    How to get the count - number of records from a .TXT file through Oracle 8i
    EMP.TXT
    EMPNO ENAME
    1 REENA
    2 SUGU
    3 RAJ
    Count(*)=3
    How to get this output in Oracle 8i.
    Thanks in advance
    Gita

    sql>create or replace directory TEST_DIR as 'd:\test';
    Directory created.
    sql>
    CREATE OR REPLACE PROCEDURE rd_file
    AS
    v varchar2(500);
    abc number;
    in_file utl_file.file_type;
    BEGIN
    in_file :=utl_file.fopen('TEST_DIR','sample.txt','R');
    abc := 0;
    loop
      utl_file.get_line(in_file,v);
      abc := abc + 1;
    end loop;
    EXCEPTION
    when no_data_found then
      utl_file.fclose(in_file);
      dbms_output.put_line(abc);
    END ;
    show errors;
    Procedure created.
    No errors
    sql>
    begin
    rd_file;
    end;
    4
    PL/SQL procedure successfully completed
    Message was edited by:
            jeneesh                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Copy  txt file to vector

    Dear anyone,
    i want to copy a txt file to a vector. But i want vector contains one word per line and not all the txt file into one line.
    I would be grateful if you could help me as soon as possible!

    For example the text file is like that : "Goodmorning
    Aris"
    and i want to put the word "Goodmorning" to the first
    row of the vector
    and the word "Aris" to the second row of the vector.
    After the word Goodmorning there is space(" ")Now we're getting somewhere. So you can either use the String method's split() method to split up the line into an array of String objects based on a delimiter (spaces in your case), or you can use the older StringTokenizer class to "tokenize" the string based on the space delimiter.
    Rather than spell out what to do in code, I'll point you to the javadocs for you to look up the String and StringTokenizer classes and play with them.
    http://java.sun.com/j2se/1.4.2/docs/api/

  • Search a txt file

    how can i search for a certain word in a txt file?

    import java.awt.*;
    import java.io.*;
    import hsa.Console;
    public class Duel_Prac
        static Console c = new Console ();
        static BufferedReader file;
        static String f_name;
        static String l_name;
        static String option = "";
        static String filedata;
        static public void main (String[] args) throws IOException
            startup_page ();
            main_menu ();
        static void startup_page ()
            c.clear ();
            c.println ("Prac");
            c.println ();
            c.println ("Before we begin, please provide us with the following information about you: ");
            c.println ();
            c.print ("First Name: ");
            f_name = c.readLine ();
            c.print ("Last Name: ");
            l_name = c.readLine ();
        static void main_menu () throws IOException
            c.clear ();
            c.println ("Prac");
            c.println ();
            c.println ();
            c.println ();
            c.print ("1) shop");
            do
                c.setCursor (3, 1);
                c.print ("What do you want do ? ");
                option = c.readLine ();
                if (option.equals ("1") == true || option.equalsIgnoreCase ("shop") == true)
                    break;
            while (!option.equals ("1") && !option.equalsIgnoreCase ("shop"));
            if (option.equals ("1") == true || option.equalsIgnoreCase ("shop") == true)
                shop ();
        static void shop () throws IOException
            try
                file = new BufferedReader (new FileReader ("Card Data/EP1-EN.masterlist"));
                if ((filedata = file.readLine ()) == null)
                    file.close ();
            catch (IOException e)
                c.println ("Data is corrupt");
            String l = "Light";
            if (filedata.equals (l))
                c.println ("Congratualations, your code is correct");
            else
                c.println ("Too bad, your code has bugs");
    }here is the code. what is wrong with it?

  • Help with program using hashtable to count words & other chars in txt file

    I need to use only a hashtable to count the occurences words and chars in a text file and display them alphabetically. I am not to use anything but the hashtable. so far, I can get it to count only the words in the file and not the chars, I want to know how to make it count the chars (,.;:?(){}[]!@#$%^&\t\"<>/`~ ) that may be found and if it is possible to get it to display them in a sorted (alphabetical) order w/o using anything else.
    This is what I have: mport java.io.*;
    import java.util.*;
    import javax.swing.JOptionPane;
    class words{
    String word;
    int count;
    public class WordCount{
    static Hashtable h=new Hashtable();
    static words w;
    static void countWords(String s){
    if((w=(words)h.get((java.lang.Object)s))==null){
    w=new words();
    w.word=s;
    w.count=1;
    h.put(s,w);
    }else{
    w.count++;
    h.remove(s);
    h.put(s,w);
    public static void main(String args[]){
    String s;
    StringTokenizer st;
    String t;
    String fn = JOptionPane.showInputDialog("Enter the filename:");
    BufferedReader br = null;
    try{
    br = new BufferedReader(new FileReader(fn));
    s=br.readLine();
    while(s!=null){
    st= new StringTokenizer(s, " ,.;:?(){}[]!@#$%^&\t\"<>/`~  ");
    // Split your words.
    while(st.hasMoreTokens()){
    t=st.nextToken();
    countWords(t);
    s=br.readLine();
    }catch(Exception e){
    e.printStackTrace();
    Enumeration e=h.elements();
    w=(words)e.nextElement();
    while(e.hasMoreElements()){
    System.out.println(w.word + " " + w.count);
    w=(words)e.nextElement();
    System.exit(0);
    }

    Please don't crosspost. It cuts down on the effectiveness of responses, leads to people wasting their time answering what others have already answered, makes for difficult discussion, and is generally just annoying and bad form.

  • Count the number of lines in a txt file

    I need to count the number of lines in a txt file, but I can't do it using readLine(). This is because the txt file is double spaced. readLine() returns null even if it is not the end of the file. thanks for the help

    I need to count the number of lines in a txt file,
    but I can't do it using readLine(). Then just compare each single byte or char to the newline (code 10).
    This is because the txt file is double spaced. readLine() returns
    null even if it is not the end of the file.Errm what? What do you mean by "double spaced"? Method readLine() should only return null if there's nothing more to read.

  • Txt file word count

    Hi,
    I have a txt file with words on it i want to count them.
    is there any command that allows me to do it ?
    Thanks

    Enter the following into the Terminal:
    wc -w
    followed by typing a space, dragging the file into the Terminal window or otherwise entering its path, and pressing Enter.
    (44078)

  • How to read the last line in a txt file?

    Dear all,
    I want to read the last line in a txt file. There are thousands of lines in this file. What I want is to move the file pointer directly to the last line of the file. But I did not know how do to it. Can anybody help me out?
    Thank you very much!

    If the file is coded as ASCII or one of the encodings that maps a single byte to a char then the following class will assist you
    import java.io.*;
    import java.util.*;
    public class GetLinesFromEndOfFile
        static public class BackwardsFileInputStream extends InputStream
            public BackwardsFileInputStream(File file) throws IOException
                assert (file != null) && file.exists() && file.isFile() && file.canRead();
                raf = new RandomAccessFile(file, "r");
                currentPositionInFile = raf.length();
                currentPositionInBuffer = 0;
            public int read() throws IOException
                if (currentPositionInFile <= 0)
                    return -1;
                if (--currentPositionInBuffer < 0)
                    currentPositionInBuffer = buffer.length;
                    long startOfBlock = currentPositionInFile - buffer.length;
                    if (startOfBlock < 0)
                        currentPositionInBuffer = buffer.length + (int)startOfBlock;
                        startOfBlock = 0;
                    raf.seek(startOfBlock);
                    raf.readFully(buffer, 0, currentPositionInBuffer);
                    return read();
                currentPositionInFile--;
                return buffer[currentPositionInBuffer];
            public void close() throws IOException
                raf.close();
            private final byte[] buffer = new byte[4096];
            private final RandomAccessFile raf;
            private long currentPositionInFile;
            private int currentPositionInBuffer;
        public static List<String> head(File file, int numberOfLinesToRead) throws IOException
            return head(file, "ISO-8859-1" , numberOfLinesToRead);
        public static List<String> head(File file, String encoding, int numberOfLinesToRead) throws IOException
            assert (file != null) && file.exists() && file.isFile() && file.canRead();
            assert numberOfLinesToRead > 0;
            assert encoding != null;
            LinkedList<String> lines = new LinkedList<String>();
            BufferedReader reader= new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));
            for (String line = null; (numberOfLinesToRead-- > 0) && (line = reader.readLine()) != null;)
                lines.addLast(line);
            reader.close();
            return lines;
        public static List<String> tail(File file, int numberOfLinesToRead) throws IOException
            return tail(file, "ISO-8859-1" , numberOfLinesToRead);
        public static List<String> tail(File file, String encoding, int numberOfLinesToRead) throws IOException
            assert (file != null) && file.exists() && file.isFile() && file.canRead();
            assert numberOfLinesToRead > 0;
            assert (encoding != null) && encoding.matches("(?i)(iso-8859|ascii|us-ascii).*");
            LinkedList<String> lines = new LinkedList<String>();
            BufferedReader reader= new BufferedReader(new InputStreamReader(new BackwardsFileInputStream(file), encoding));
            for (String line = null; (numberOfLinesToRead-- > 0) && (line = reader.readLine()) != null;)
                // Reverse the order of the characters in the string
                char[] chars = line.toCharArray();
                for (int j = 0, k = chars.length - 1; j < k ; j++, k--)
                    char temp = chars[j];
                    chars[j] = chars[k];
                    chars[k]= temp;
                lines.addFirst(new String(chars));
            reader.close();
            return lines;
        public static void main(String[] args)
            try
                File file = new File("/usr/share/dict/words");
                int n = 10;
                    System.out.println("Head of " + file);
                    int index = 0;
                    for (String line : head(file, n))
                        System.out.println(++index + "\t[" + line + "]");
                    System.out.println("Tail of " + file);
                    int index = 0;
                    for (String line : tail(file, "us-ascii", n))
                        System.out.println(++index + "\t[" + line + "]");
            catch (Exception e)
                e.printStackTrace();
    }Note, the EOL characters are treated as line separators so you will probably need to read the last two lines (think about it for a bit).

Maybe you are looking for