Reading text file and output (to stdout) a list of the unique words in the

Hi,
I have a main method as
main.java
package se.tmp;
public class Main
public static void main( String[] args )
WordAnalyzer.parse( args[0] );
and text file as
words.txt
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the quick brown fox jumps over the lazy dog
the requirement is like
I need create this WordAnalyzer class, implement the parse method, and then commit the file. This method takes a single parameter, the filename of the file to parse. The method should read this file and output (to stdout) a list of the unique words in the file along with the number of times each appears in the file.
Can anyone please help me on this?
Thanks.

Where are you having problems?

Similar Messages

  • Read text file and insert into MySQL

    Dears,
    I need to read text file and then insert the data in the correct column in the MySQL database
    example
    I have the following text file:
    field1=1234 field2=56789 field3=444555
    field1=1333 field2=2222 field3=333555
    and so on and so forth ,,note that all rows are identical and just the filed value is changed(there is a dilemeter between fields)
    how can I read field1,field2 and field3 from text file and insert them in the correct table and column in the database.....
    any help?????
    thanks for your cooperation
    Best Regars

    Sure.
    Which part don't you understand?
    1. Reading a text file
    2. Parsing the text file contents.
    3. Relational databases and SQL.
    4. How to create a database.
    5. How to connect to a database in Java.
    6. How to insert records into the database in Java.
    7. How to map Java objects to records in a database.
    This is a pretty nice list. Solve complex problems by breaking them into smaller ones.
    %

  • Read Text file and count occurences of certain string

    Hello,
    I have a text file with lines of data in it. I would like to read this text file and count how many lines match a certain string of text. 
    For example my text file has this data in it.
    dog,blue,big
    dog,red,small
    dog,blue,big
    cat,blue,big
    If the certain string of text is "dog,blue,big" then the count would return "2".
    Thanks for your help

    Hello,
    Thank you for your post.
    I am afraid that the issue is out of support range of VS General Question forum which mainly discusses the usage issue of Visual Studio IDE such as
    WPF & SL designer, Visual Studio Guidance Automation Toolkit, Developer Documentation and Help System
    and Visual Studio Editor.
    I am moving your question to the moderator forum ("Where is the forum for..?"). The owner of the forum will direct you to a right forum.
    In addition, if you are working with Windows Forms app. please consult on Windows Forms Forum:http://social.msdn.microsoft.com/Forums/windows/en-US/home?category=windowsforms
    If you are working with WPF app, please consult on WPF forum:
    http://social.msdn.microsoft.com/Forums/vstudio/en-US/home?forum=wpf
    If you are working with ASP.NET Web Application, I suggest that you can consult your issue on ASP.NET forum:
    http://forums.asp.net/
     for better solution and support.
    Visual Studio Language Forums:
    http://social.msdn.microsoft.com/Forums/vstudio/en-US/home?category=vslanguages
    Best regards,
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Compare data from 2 text files and output match

    Hi all,
    I need some advice.
    Firstly in BinaryCode.txt the data is as such:
    Replace BinaryCode0 1 0 0 0 0 0 0 0 0
    Replace BinaryCode0 1 0 0 0 0 0 0 0 1
    Replace BinaryCode1 1 1 1 0 1 1 1 1 1
    Replace BinaryCode1 1 0 0 0 0 0 0 0 0
    the first line in the text file is the header. So I need to check if the names in the second column (BinaryCode0 or BinaryCode1)appear in the Timed_Sets.txt file.
    The data in Timed_Sets.txt is as such:
    BinaryCode0,6,40,.........................
    BinaryCode0,7,40,.........................
    BCName1,0,20,.............................
    BCName1,1,20,............................. 
    For example since  BinaryCode0 is a match I will output the entire row in Timed_Set.txt to another array. 
    I have been working on a program but I don't get the expected output. 
    The text files and the VI are attached.
    I appreciate your kind assistance in the matter.
    Thank You
    Regards
    kart 
    Solved!
    Go to Solution.
    Attachments:
    BinaryCode.txt ‏1 KB
    compare text files.vi ‏15 KB
    Timed_Sets.txt ‏2 KB

    If I understood correctly what the output should be then what you basically need to do is to walk through the column in BinaryCode.txt and for each unique value pull out the corresponding rows from Timed_Sets.txt. There's a variety of ways to do this, depending on how much data you have and whether or not you can use any kind of prior knowledge as to the actual file content (such as the names of the keys being searched). Attached is one way. Modify as needed.
    Attachments:
    compare text files MOD.vi ‏27 KB

  • Reading text files and EOF

    I am attempting to read in blocks of data from a text file separated by a blank line. When the BufferedReader hits the first blank line it ends. I retyped the test text file and still cannot get it to continue to read the entire file; just the first block.
    fReader = new FileReader( textFile );
    bReader = new BufferedReader( fReader );
    line = bReader.readLine();
    while( line ! = null ){
    do stuff;
    bReader.close()
    The format of my textFile is:
    100
    some name
    type 1
    type 2
    101
    some other name
    type 1
    type 2
    Any suggestions would be greatly appreciated.

    Hi,
    I saw that BigDaddyLoveHandles already helped you a lot but I wanted to add a little something to that, because from what I understood you need to keep the blocks together.
    public static void main(String[] args) {
              BufferedReader theReader = null;
              try {
                   theReader = new BufferedReader(new FileReader("pathToYourFile"));
                   String line;
                   StringBuilder theBuilder = new StringBuilder();
                   while ((line = theReader.readLine()) != null){
                        if (line.isEmpty()){
                             doStuff(theBuilder.toString());
                             theBuilder = new StringBuilder();
                        }else {
                             theBuilder.append(line).append(System.getProperty("line.separator"));
                   doStuff(theBuilder.toString());
              } catch (IOException e) {
                   e.printStackTrace();
              } finally{
                   if (theReader != null)
                        try {
                             theReader.close();
                        } catch (IOException e) {
                             e.printStackTrace();
         }This actually allows your method doStuff to get the whole block vs. line by line.
    Regards

  • Read Zip File and output it to the Stream

    Hi,
    I really need help with this topic. I need to write a function which as input read the zip file (inside: jpeg, mp3, xml)
    and as output provide the output Stream of this zip file.
    public OutputStream readZipToStream(String sourceZipFile) { ....}
    I've tried something....
    public static OutputStream    readZipToStream(String src, HttpServletResponse response) throws Exception {
            File fsrc = null;
            ZipOutputStream out = null;
            byte buffer [] = null;
            FileInputStream in = null;
            try {
                buffer = new byte[BUFFER_CREATE];
                fsrc = new File(src);
                out = new ZipOutputStream(response.getOutputStream());
                ZipEntry zipAdd = new ZipEntry(fsrc.getName());
                zipAdd.setTime(fsrc.lastModified());
                out.putNextEntry(zipAdd);
                // Read input & write to output
                in = new FileInputStream(fsrc);
                while (true) {
                    int nRead = in.read(buffer, 0, buffer.length);
                    if (nRead <= 0)
                        break;
                    out.write(buffer, 0, nRead);
                out.flush();
                in.close();
            } catch (IOException ioe) {
                logger.error("Zip Exception: " + ioe.getMessage());
                ioe.printStackTrace();
                throw ioe;
            return out;
        } But the problem with this code when it returns ( I called from servlet: bellow)
    it ask user to save the file as servlet.jsp file. So I would have to rename it to zip file later.
    What I want to achive is it would ask to save zip file from the stream as name of the original zip file (if that is possible)
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <%
    OutputStream stream = null;
    response.setContentType("application/zip");
    target = mount_media + File.separator + "test_swf.zip";       
    try {
    stream = ZipUtil.readZipToStream(target, response);
    } catch (Exception ex) {
            System.out.println(ex.getMessage());
        } finally {
    if(stream != null) {
                stream.close();
    %>
    <%@page import="java.io.File" %>
    <%@page import="java.io.OutputStream" %>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    </head>
    <body>
    </body>
    </html>

    Hi oleg_s ,
    There's a contradiction of content in your JSP :
    response.setContentType("application/zip");
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">The html part of your JSP seems useless for what you mean to do. Therefore, instead of a JSP, you should use a simple servlet to send your zip file.

  • Reading text file and display in the selectOnechoice list item In ADF.

    Hi,
    I have a requirement to read the text field which have list of strings and that string display in the SelectOneChoice List item component on page load.
    I am using Jdeveloper 11.1.2.3 version.
    Any suggestion will highly appreciated..
    Thanks in advance.
    Regards

    Hi,
    Google will produce you with hints on how to read content of a file from Java (ideally the file uses some delimiter). Then in a managed bean, you read the file and save its content in a list of SelectItem. So your managed bean should have the following property and setter/getter pairs
    ArrayList<SelectItem> listFromFile = new ArrayList<SelectItem>();
    public void setListFromFile(ArrayList l){ //you don't need this }
    public ArrayList<SelectItem> getListFromFile(){
       //read file content and iterate over the file list entries
      for(i=0, i < fileContent.length, ++i){
         SelectItem si = new SelectItem();
         si.setValue(... the value to update the list of value with ...);
         si.setLabel("... the label to show in the list ...");
         listFromFile.add(si);
      return listFromFile;
    }The af:selectOneChoice component should look as follows
    <af:selectOneChoice id=".." value="...attribute to update with selection ..." ...>
       <f:selectItems value="#{managedBean.listFromFile}"/>
    </af:selectOneChoice>Frank

  • Read text file and split up.  How???

    Can anyone tell me how to split up a string into words.
    The string is: "me and my cat both like milk and cookies"
    I need read through the file and diplay the biggest word(s) and the smallest word(s).
    I would appriciate help on this as i am really stumped
    Thanks
    ..::M::..
    p.s. I also need to be able to do this in C++ but if i know it in java i think the C++ will be simple

    String[] words = "your sentencehere".split("\\s+");
    and now you have array of strings, each containigwords from text.
    this is helpful, is there a version in C++ tooThe short answer for C++ is "no". Unless of course you install one of the regexp libraries available. But there is no native language way to do it like in Java.
    However if they words always have spaces and always will have spaces you can write your C++ code like this:
    vector <string> words;
    ifstream inFile( "file.txt" );
    string temp;
    inFile >> temp;
    words.push_back( temp );
    PS I have not tested this code in anyway but it should be simple enough

  • How to read text file and store in database

    Respected All,
    I have text file on my computer.
    I am using forms6i and oracle 9i.
    I want that when i press button then specifice world in text file is read and dispaly on form to be stored in database.
    Please provide some solution.
    Kind Regards

    Hello,
    Study the functions of the TEXT_IO() package
    http://www.oracle.com/webapps/online-help/forms/10g/state?navSetId=_&navId=3&vtTopicFile=f1_help/oraini/c_text_io.html&vtTopicId=
    Francois

  • How to read a text file and write text file

    Hello,
    I have a text file A look like this:
    0 0
    0 A B C
    1 B C D
    2 D G G
    10
    1 A R T
    2 T Y U
    3 G H J
    4 T H K
    20
    1 G H J
    2 G H J
    I want to always get rid of last letter and select only the first and last line and save it to another text file B. The output should like this
    0 A B
    2 D G
    1 A R
    4 T H
    1 G H
    2 G H
    I know how to read and write a text file, but how can I select the text when I am reading a text file. Can anyone give me an example?
    Thank you

    If the text file A look like that
    0 0
    0 3479563,41166 6756595,64723 78,31 1,#QNAN
    1 3479515,89803 6756588,20824 77,81 1,#QNAN
    2 3479502,91618 6756582,6984 77,94 1,#QNAN
    3 3479516,16334 6756507,11687 84,94 1,#QNAN
    4 3479519,14188 6756498,54413 85,67 1,#QNAN
    5 3479525,61721 6756493,89255 86,02 1,#QNAN
    6 3479649,5546 6756453,21824 89,57 1,#QNAN
    1 0
    0 3478762,36013 6755006,54907 54,8 1,#QNAN
    1 3478756,19538 6755078,16787 53,63 1,#QNAN
    2 0
    3 0
    N 0
    I want to read the line that before and after 1 0, 2 0, ...N 0 line to arraylist. I have programed the following code
    public ArrayList<String>save2;
    public BufferedWriter bufwriter;
    File writefile;
    String filepath, filecontent, read;
    String readStr = "" ;
    String[]temp = null;
    public String readfile(String path) {
    int i = 0;
    ArrayList<String> save = new ArrayList <String>();
    try {
    filepath = "D:\\thesis\\Material\\data\\CriticalNetwork\\test3.txt";
    File file = new File(filepath);
    FileReader fileread = new FileReader(file);
    BufferedReader bufread = new BufferedReader(fileread);
    this.read = null;
    // read text file and save each line content to arraylist
    while ((read = bufread.readLine()) != null ) {
    save.add(read);
    // split each arraylist[i] element by space and save it to String[]
    for(i=0; i< save.size();i++){
    this.temp = save.get(i).split(" ") ;
    // if String[] contain N 0 such as 0 0, 1 0, 2 0 then save its previous and next line from save arraylist to save2 arraylist
    if (temp.equals(i+"0")){
    this.save2.add(save.get(i));
    System.out.println(save2.get(i));
    } catch (Exception d) {
    System.out.println(d.getMessage());
    return readStr;
    My code has something wrong. It always printout null. Can anyone help me?
    Best Regards,
    Zhang

  • Read from .txt file and output the content as two arrays

    I am using the contoured move to control the x-y stage. The trajectory datas for x and y axis are generated using my interpolation program and it is stored in a .txt file as two columns. What I want to do is read .txt file and output the content of this file as two arrays. Is there anyone has any ideas? Thanks, the .txt file is attached.
    Attachments:
    R.75.txt ‏172 KB

    Hi Awen,
    This is quite easy to do, you can merely use the "read from spreadsheet file" function to get a 2D array (2 columns and n rows) and then use the index array function to get whatever row/colums you want..
    Hope the attached VI helps you
    When my feet touch the ground each morning the devil thinks "bloody hell... He's up again!"
    Attachments:
    read sprdsheet file.vi ‏27 KB

  • Where does this java program read a text file and how does it output the re

    someone sent this to me. its a generic translator where it reads a hashmap text file which has the replacement vocabulary etc... and then reads another text file that has what you want translated and then outputs translation. what i don't understand is where i need to plugin the name of the text files and what is the very first line of code?
    [code
    package forums;
    //references:
    //http://forums.techguy.org/development/570048-need-write-java-program-convert.html
    //http://www.wellho.net/resources/ex.php4?item=j714/Hmap.java
    import java.util.Map;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.BufferedReader;
    import java.io.FileReader;
    public class Translate {
    public static void main(String [] args) throws IOException {
    if (args.length != 2) {
    System.err.println("usage: Translate wordmapfile textfile");
    System.exit(1);
    try {
    HashMap words = ReadHashMapFromFile(args[0]);
    System.out.println(ProcessFile(words, args[1]));
    } catch (Exception e) {
    e.printStackTrace();
    // static helper methods
    * Reads a file into a HashMap. The file should contain lines of the format
    * "key\tvalue\n"
    * @returns a hashmap of the given file
    @SuppressWarnings("unchecked")
    private static HashMap ReadHashMapFromFile(String filename) throws FileNotFoundException, IOException {
    BufferedReader in = null;
    HashMap map = null;
    try {
    in = new BufferedReader(new FileReader(filename));
    String line;
    map = new HashMap();
    while ((line = in.readLine()) != null) {
    String[] fields = line.split("\\t", 2);
    if (fields.length != 2) continue; //just ignore "invalid" lines
    map.put(fields[0], fields[1]);
    } finally {
    if(in!=null) in.close(); //may throw IOException
    return(map); //returning a reference to local variable is safe in java (unlike C/C++)
    * Process the given file
    * @returns String contains the whole file.
    private static String ProcessFile(Map words, String filename) throws FileNotFoundException, IOException {
    BufferedReader in = null;
    StringBuffer out = null;
    try {
    in = new BufferedReader(new FileReader(filename));
    out = new StringBuffer();
    String line = null;
    while( (line=in.readLine()) != null ) {
    out.append(SearchAndReplaceWordsInText(words, line)+"\n");
    } finally {
    if(in!=null) in.close(); //may throw IOException
    return out.toString();
    * Replaces all occurrences in text of each key in words with it's value.
    * @returns String
    private static String SearchAndReplaceWordsInText(Map words, String text) {
    Iterator it = words.keySet().iterator();
    while( it.hasNext() ) {
    String key = (String)it.next();
    text = text.replaceAll("\\b"+key+"\\b", (String)words.get(key));
    return text;
    * @returns: s with the first letter capitalized
    String capitalize(String s)
    return s.substring(0,0).toUpperCase() + s.substring(1);
    }

    without what arguments?Without any arguments. If there are no arguments, there are no arguments of any kind. If you have a zoo with no animals in it, it's not meaningful to ask whether the animals which are not there are zebras or elephants.
    does it prompt me to give it a text file name?Apparently.
    when i run it this is all i get:
    usage: Translate wordmapfile textfile
    Press any key to continue...Right. And "wordmapfile" is almost certainly supposed to be a file that holds the word map, and "textfile" is almost certainly the file of text that it's going to translate.

  • How to read a text file and only output every other line?

    I am just writing a program that reads a file but outputs only every other line. Any ideas...please? thanks

    I'd start with something like this and expand on it as you go:
    File file = <whatever>;
    BufferedReader in = null;
    try {
        in = new BufferedReader(new FileReader(file));
        int i = -1;
        for (String line = null; (line = in.readLine()) != null; ) {
            if ((++i % 2) == 0) {
                System.out.println(line);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
    }Shaun

  • Urgent Help:read from text file and write to table

    Hi,
    I'm a super beginner looking for a vi to read this data from a text file and insert it into a table:
       #19
    Date: 05-01-2015
    ID= 12345678
    Sample_Rate= 01:00:00
    Total_Records= 2
    Unit: F
       1 03-23-2015 10:45:46   70.1   3.6
       2 03-23-2015 11:45:46   67.7   2.7
    Output table
    #     date                 time                 x          y        Sample rate    Total Records
    1          03-23-2015     10:45:46        76.8     2.8      01:00:00           2
    2          03-23-2015     10:45:46        48.7     2.1      01:00:00           2
    Thanks for your help in advance.
    Attachments:
    sample.txt ‏1 KB

    jcarmody wrote:
    Will there always be the same number of rows of noise header information?
    Show us how you've read the data and what you've tried to do to parse it.  Once you've got the last rows, you can loop over them using Spreadsheet String to Array (after cleaning up a few messy spaces).
    Jim,
    I didn't know you're that active on here.
    Yes, There will always be the same number of noise header information.
    I'll show you in person
    Regards,

  • Issue : Read a text file and print the same

    Hi, My requirement is to read a text file and print it the same way.
    import java.io.BufferedReader;
    import java.io.FileReader;
    public class CatFile {
    public static void main(String[] args) throws Exception
         FileReader file = new FileReader("D:/Test/Allfiles.txt");
         BufferedReader reader = new BufferedReader(file);
         String text = "";
         String line = reader.readLine();
         while (line != null)
              text += line;
              line = reader.readLine();
         System.out.println(text);
    The text file i used contains
    A
    B
    C
    but my output is ABC.
    What change should be made to print it the same way in the txt file ?

    Hi EJP,
    I modified the code based on your suggestion and now its working as expected. Thanks
    Modified code :
    import java.io.BufferedReader;
    import java.io.FileReader;
    public class CatFile {
    public static void main(String[] args) throws Exception
         FileReader file = new FileReader("D:/Test/Allfiles.txt");
         BufferedReader reader = new BufferedReader(file);
         String text = "";
         String line = reader.readLine();
         while (line != null)
              System.out.println(line);
              line = reader.readLine();
              text += line;
    }

Maybe you are looking for