To get  a  word in the text  file

Hi,
I m beginner to java.
HOw i get a word in the text file.
I used this code, it is only display the all sentence which are available in the text file.
But , I need to print particular word (if it is available in that text file)
package com.beryl;
import java.io.*;
class FileReadTest {
public static void main (String[] args) {
     FileReadTest f = new FileReadTest();
f.readMyFile();
void readMyFile() {
     BufferedReader dis =null;
String record = null;
int recCount = 0;
try {
File f = new File("E:/hello/abc.txt");
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis);
dis
= new BufferedReader(new InputStreamReader(bis));
while ( (record=dis.readLine()) != null ) {
recCount++;
System.out.println(recCount + ": " + record);
} catch (IOException e) {
// catch io errors from FileInputStream or readLine()
System.out.println("Uh oh, got an IOException error!" + e.getMessage());
} finally {
// if the file opened okay, make sure we close it
if (dis != null) {
     try {
dis.close();
     } catch (IOException ioe) {
Thanks & Regards,
kumar

I used this code, it is only display the all
sentence which are available in the text file.
But , I need to print particular word (if it
is available in that text file)if
String.indexOf()

Similar Messages

  • How can i insert the text file in a hashSet???

    Hi, here's the code to feed the text file into the program, i need to put the words from the text file into a hashSet, im not too sure how to go about doing this, can anyone help please?
    import java.io.*;
    public class FileIn {
    BufferedReader in;
    public FileIn() {
    try {
    in = new BufferedReader(new FileReader("\\C:\\Program Files\\java.txt\\"));
    String line = in.readLine();
    System.out.println(line);
    in.close();
    } catch(IOException ioe) {
    System.out.println(ioe.toString());
    public static void main(String args[]) {
    FileIn newFile = new FileIn();
    }

    First you need to break each line into words. You'll need to decide on your rules for doing that. A simple approach would be to just break on whitespace. This assumes there are no hyphenated words at the end of a line. You'll also want to strip out punctuation.
    Once you've got a word (or an array of them, if you used String.split), then just iterate over it and call HashSet.add for each one. There might even be a helper function in java.util.Arrays or java.util.Collections or in HashSet to add everything from an array.
    http://java.sun.com/docs/books/tutorial/collections/

  • Replace/cut part of words from a text file.

    Hello Hello everyone, I have a quick question. I have my text file that contains also words like ... let's say abc1, abc2 and so on, and I need to cut the c from the word, I need ab1, ab2.
    Here is what I have started:
    import java.util.*;
    import java.io.*;
    public class test
            Vector<String> x = new Vector<String>();
    public mergefiles() throws IOException
            readAdd("test.txt");
            write("testout.txt");    
    private void readAdd(String name) throws IOException
            BufferedReader reader = new BufferedReader(new FileReader(name));
            String line,all=new String();
            while ((line = reader.readLine ()) != null)
                    all+=line+'\n';
            reader.close ();
            int posX=all.indexOf("X"); // x being like first word of the text file
              if (all.length()-posX>0)
                   String between=all.substring(posX+3,all.length());
                   StringTokenizer st=new StringTokenizer(between," \n");
    private void write(String name) throws IOException
            BufferedWriter writer = new BufferedWriter(new FileWriter(name));
            String s=new String();
             if (x.size()>0)
                  s+="X"+'\n';
             s+='\n';
             writer.write(s);
            writer.close();
    public static void main(String[] args) throws IOException
            new test();
    }I am new to Java and I would really appreciate if you would be patient with me.
    Thank you!

    I have tried in readAdd method something like:
    int posX=all.indexOf("X"); // x being like first word of the text file
              if (all.length()-posX>0)
                   string.replace("ab1","abc1");
              }     but still doesn't work, and this is not a really good ideea, in case that I have to replace 1000 of abci ...I should use a for in my write method:
    String[] s=new String[2];
    for(int i=0;i<word.length;i++)
                   BufferedWriter writer = new BufferedWriter(new FileWriter(testout.substring(0, testout.lastIndexOf("."))+(i+1)+".txt"));
                       writer.write(s);
              writer.close();
    But I not really sure if this is ok! Right now nothing is working
    Thanks                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Scanner cant find the text file??

    Hello guys,
    I have a java program that is designed to generate maze out of text files. So basically it takes a text file and uses the info to set up a maze through GUI. The program was written by my professor and i cant get it to run the text files. When i run the program a gui pops up and assks me to enter one of eight text files.
    They are labeled maze1.txt to maze8.txt
    So once i enter the file, the programs tells me that the files can not be found. I have all eight maze files saved in the source folder. So i assume i dont have to import anything. If it helps any here is how the project set up looks like in eclipse? I have to assume that i have not set up something correctly as the program should work.
    Here is the pic of my eclipse setup:
    [http://img.photobucket.com/albums/v395/merlin77/maze.jpg]
    What am i doing wrong?
    Thanks for your help,
    Edited by: Lovac on Oct 8, 2008 10:05 PM

    Sorry i should have provided more information. Here is how his constructor for Maze class looks like:
         public Maze(String fname) throws FileNotFoundException {
              Scanner sc = new Scanner(new File(fname));
              int r, c;
              r = sc.nextInt();
              c = sc.nextInt();
              m = new int[r + 2][c + 2];
              for (int j = 0; j < c + 2; j++) {
                   m[0][j] = -1;
                   m[r + 1][j] = -1;
              for (int i = 0; i < r + 2; i++) {
                   m[0] = -1;
                   m[i][c + 1] = -1;
              for (int i = 1; i <= r; i++) {
                   for (int j = 1; j <= c; j++) {
                        m[i][j] = sc.nextInt();
              sc.close();
    As you can see above the text file is just passed to constructor as a parameter, and i am thinking when i run the program and it asks me for the text file, i just give it the file name ex. "maze1.txt" and that would be the parameter to the Maze constructor. BUT then the constructor fails to find the file and from what i know that is due to files eather not being imported in the java class or because they are missing from the source folder?
    But clearly i have them in the source folder, so importing them in java class would be pointless. The compiler should be able to find them in the source folder.
    I guess i can forward this question to Professor, but i thought there was something simple that i am missing.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Need help to add the words in a text file to an arraylist

    I am new to java and I really need some help for my project.I want to add the words of a text file to an arraylist. The text file consist of words and the following set of punctuation marks {, . ; : } and spaces.
    thanks in advance :-)

    I/O: [http://java.sun.com/docs/books/tutorial/essential/io/index.html]
    lists and other collections: [http://java.sun.com/docs/books/tutorial/collections/index.html]

  • When I import IE8 bookmarks into Firefox Portable, the text files or downloaded Google searches or other downloaded websites that I saved and added to my various Favorites folders do not appear ... and (2) if I can get them to appear, will I continue to b

    When I import IE8 bookmarks into Firefox Portable, the text files or downloaded Google searches or other downloaded websites that I saved and added to my various IE8 Favorites folders do not appear ... and (2) if I can get them to appear, will I still be able to add text files to the Firefox Favorites folders ... and how.
    == User Agent ==
    Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)

    http://portableapps.com/forums/support/firefox_portable

  • Search for a word and return all the  lines (row) from the text file..

    Hi all,
    I need a help on how to search a string from the text file and returns all the lines (rows) where the searched string are found. I have included the code, it finds the indexof the string but it does not return the entire line. I would appreciate your any help.
    public class SearchWord
         public static void main(String[] args){
         //Search String
         String searchText = "man";
         //File to search (in same directory as .class file)
         String fileName = "C:\\Workspace\\MyFile.txt";
         //StringBuilder allows to create a string by concatinating
         //multiple strings efficiently.
         StringBuilder sb =
         new StringBuilder();
         try {
         //Create the buffered input stream, which reads
         //from a file input stream
         BufferedInputStream bIn =
         new BufferedInputStream(
         new FileInputStream(fileName));
         //Holds the position of the last byte we have read
         int pos = 0;
         //Holds #of available bytes in our stream
         //(which is the file)
         int avl = bIn.available();
         //Read as long as we have something
         while ( avl != 0 ) {
         //Holds the bytes which we read
         byte[] buffer = new byte[avl];
         //Read from the file to the buffer
         // starting from <pos>, <avl> bytes.
         bIn.read(buffer, pos, avl);
         //Update the last read byte position
         pos += avl;
         //Create a new string from byte[] we read
         String strTemp =
         new String(buffer);
         //Append the string to the string builder
         sb.append(strTemp);
         //Get the next available set of bytes
         avl = bIn.available();
         catch(IOException ex) {
         ex.printStackTrace();
         //Get the concatinated string from string builder
         String fileText = sb.toString();
         int indexVal = fileText.indexOf(searchText);
         //Displays the index location in the file for a given text.
         // -1 if not found
         if (indexVal == -1)
              System.out.println("No values found");
         else
              System.out.println("Search for: " + searchText);     }
    }

    Hi, you can use servlet class and use this method to get the whole line of searched string. You can override the HttpServlet to treat that class as servlet.
    public class ReportAction extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    //write your whole logic.
    BufferedReader br = new BufferedReader(new FileReader("your file name"));
    String line = "";
    while(line = br.readLine() != null) {
        if(line.contains("your search string")) {
            System.out.println("The whole line, row is :"+line);
    }

  • Word count in text file

    Hi,
    I am trying to count word in my text file by using the Java code. Even though i am error in the code and don't know what sintaks to use. For example:
    I have
    school 4
    bus 3
    student 5
    in a.txt
    Another text file
    bus 2
    school 2
    in b.txt
    I want to display in new text file: c.txt
    school 6 4 : a.txt 2 : b.txt
    bus 5 3 : a.txt 2 : b.txt
    student 5 5 : a.txt
    Could you please advise,what sintak that i could use??
    Thanks you..

    Use StringTokenizer object and HashMap Object
    example
    String str = (your text readed from file A)
    StringTokinzed token = new StringTokinzed(str);
    while (token.hasMoreTokens()) {
    String word = token.nextToken()
    Integer i = (Integer) hashmap.get(word);
    if (i==null) {
    i = new Integer(1);
    }else
    i++;
    hashmap.put(word,i);
    same code for B file
    iterate through the hasmap and print all word with the count

  • Find words within a text file

    Hey all.
    I am playing around with the idea of finding a line of text within a text file, by using scanner and some next methods.
    The way I am trying to get it to work is that one enters a string and the program then finds all the lines of text containing that
    user-entered string and then prints them.
    The text file in question contains names of University papers and their room numbers, quantity of students etc.
    Example:
    IBUS212     EALT006     1am     72     AL     LI     
    BMSC241     MCLT102     2     pm     8     AL     COOREY     
    My problem annoyingly enough seems to be that I can't think how one could compare the string entered to the lines of text being
    scanned in the text file.
    My latest go involved what you see in the code, scanning the examdata.txt file for a user-entered course number, using course.next();
    by going with the example above it would be IBUS212. The task was to then to find all of the lines containing that number and print them out using
    println (what I have tried with id and line) as well as the rest of that line eg: EALT006     1am     72     AL     LI .
       public void printCourse()
        try
            String details, input, id, line;
            int count;
            Scanner user = new Scanner(System.in);
            System.out.println();
            System.out.println();
            System.out.println("Please enter your course ID: ");
            input = user.nextLine();
            Scanner course = new Scanner(new File("examdata.txt"));
            course.next();
            course.nextLine();
            id = course.next();
            line = course.nextLine();
            if(input.equals(id))
                System.out.println("Your course times are: "  + id + "and" + line);
            else
              System.out.println("Your course does not exist."); 
            catch(IOException e)
                System.out.print("File failure");
      }Any advice/help/troubleshooting would be greatly appreciated.
    Edited by: AUAN on Aug 13, 2009 9:43 AM
    Edited by: AUAN on Aug 13, 2009 9:44 AM
    Edited by: AUAN on Aug 13, 2009 9:49 AM

    You'll want [to loop while|http://java.sun.com/docs/books/tutorial/java/nutsandbolts/while.html] the course Scanner has a next line and then print the line if it contains the entered text.
    For useful methods you can check the Javadoc of String and Scanner (use your browser search on keywords like 'next' or 'contains' to find them).

  • How to make an applet to read the Text file present inside a jar

    Hi All,
    I have writen one applet named ReadFile.java which reads a text file present in the same directory and does some manipulation of text file contents.
    The applet code runs successfully when i run the applet in command prompt like
    {color:#ff0000}*java ReadFile*{color}
    And i am getting the needed results.
    Then i made a jar file with the applet code and text file as
    {color:#ff0000}*jar cvf rf.jar ReadFile.class File1.txt*{color}
    Then i have inlcuded this applet inside a html file as
    {color:#ff0000}*<applet code= "ReadFile.class" width= "500" height= "300" archive = "rf.jar" ></applet>*{color}
    after this when i load the html file, the applet code is not executed fully. Its throwing FileNotFoundException: File1.txt.
    Applet is not recognizing trhe text file present inside the jar file.
    Can any body explain me how to overcome this problem. Any setting needs to be done for making the applet indicate the presence of Text file inside the jar file.

    what code in your applet gets the text file and reads it? are you using getResource or something similar?

  • How to get summary columns in delimited text file

    How to get summary columns in delimited text file
    I am trying to generate a delimited text file output with delimited_hdr = no.The report is a Group above report with summary columns at the bottom.In the text file the headers are not getting repeated & thats ok.The problem is the summary data is getting repeated for each row of data.Is there a way where i will get all the data & summary data will get displayed only once.I have to import the delimited text file in excel spreadsheet.

    Sorry there were a typos :
    When I used desformat=DELIMITEDDATA with desttype=FILE, I get error "unknown printer driver DELIMITEDDATA". When you look for help, DELIMITED is not even listed as one of the values for DESTFORMAT. But if you scroll down and look for DELIMITER it says , this works only in conjuction with DESTFORMAT=DELIMITED !!!!!!??!! This is in 9i.
    Has this thing worked for anybody ? Can anyone please tell if they were able to suppress the sumary columns or the parent columns of a master-detail data for that matter ?

  • Error in Downloading the Text file on Application Server

    Hi All,
              I am working on ECC6.0. I have written a program in whcih I am downloading the text file on
              application server in UTF-8 format. However when I am opening this file in Excel I am getting
              garbage value for some characters(as Excel does not support UTF-8 format). So now I
              want to download the data on application server in text file in non unicode format(Like ANSI or
              other non unicode format) which is supported by excel. When I am writing the code as
              OPEN DATASET DN_FILE FOR OUTPUT IN LEGACY TEXT MODE it is giving me dump saying
              CHARACTER CONVERSION FROM CODE PAGE '4102' to CODEPAGE '1100' NOT POSSIBLE.
              Same in case if I add the code OPEN DATASET DN_FILE FOR OUTPUT IN LEGACY TEXT
              MODE CODE PAGE '8000' is also giving dump.
              So please let me know how can I download the file in non unicode format ?
              Any help would be greatly appricated.
    Thanks & Regards
    Jitendra Gujarathi.

    OPEN DATASET l_filename FOR INPUT IN TEXT MODE  ENCODING NON-UNICODE IGNORING CONVERSION ERRORS.
    CHECK sy-subrc EQ 0.
      DO.
        CLEAR wa_file_content.
        READ DATASET l_filename INTO wa_file_content.
        IF sy-subrc EQ 0.
          APPEND wa_file_content TO it_file_content.
        ELSE.
          EXIT.
        ENDIF.
      ENDDO.
      CLOSE  DATASET l_filename.
      t_filedata[] = it_file_content[].
    can you use like this.

  • Sending the text file in ECC 6.0

    Hi All ,
    Note: I searched the so many forums about this but didnt not get the correct solution so I am posting this.
    In 4.7 version i used the FM SO_NEW_DOCUMENT_ATT_SEND_API1 to generate the Text file, and it is working good. but now after the upgrdation to ECC 6.0 version , same program with this FM is not working same like 4.7 version.
    Is there any thing need to add or remove or Any SAP NOTE related to this?
    Thanks in advance.
    Regards,
    Bharani

    Bharani,
    I am using the same FM in ECC 6.0.   Check your data declarations. There may be a change there.
    Regards
    MPersson
    * data declarations for sending Email
    DATA:   w_text(100) TYPE c.
    DATA    w_date(10) TYPE c.
    DATA    w_url(25) TYPE c.
    DATA:   w_subject(50)   TYPE c.
    DATA:   it_packing_list LIKE sopcklsti1 OCCURS 0 WITH HEADER LINE,
            it_contents     LIKE solisti1   OCCURS 0 WITH HEADER LINE,
            it_receivers    LIKE somlreci1  OCCURS 0 WITH HEADER LINE,
            it_attachment   LIKE solisti1   OCCURS 0 WITH HEADER LINE,
            gd_cnt          TYPE i,
            gd_sent_all(1)  TYPE c,
            gd_doc_data     LIKE sodocchgi1,
            gd_error        TYPE sy-subrc.
    DATA:   it_message TYPE STANDARD TABLE OF solisti1 INITIAL SIZE 0
                                                     WITH HEADER LINE.
    * ~~~~~~~~~~~~~~ further along in your program ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      CLEAR w_url.
    * (SENDS Copy TO USER - confirms email ) 
        it_receivers-receiver   = w_url.
        it_receivers-rec_type   = 'U'.
        it_receivers-com_type   = 'INT'.
        it_receivers-notif_del  = 'X'.
        it_receivers-notif_ndel = 'X'.
        APPEND it_receivers.
      CLEAR gd_error.
    * Call the FM to post the message to SAPMAIL
      CALL FUNCTION 'SO_NEW_DOCUMENT_ATT_SEND_API1'
        EXPORTING
          document_data              = gd_doc_data
          put_in_outbox              = 'X'
          commit_work                = 'X'
        IMPORTING
          sent_to_all                = gd_sent_all
        TABLES
          packing_list               = it_packing_list
          contents_txt               = it_message
          receivers                  = it_receivers
        EXCEPTIONS
          too_many_receivers         = 1
          document_not_sent          = 2
          document_type_not_exist    = 3
          operation_no_authorization = 4
          parameter_error            = 5
          x_error                    = 6
          enqueue_error              = 7
          OTHERS                     = 8.
    * Store function module return code
      gd_error = sy-subrc.

  • I can´t edit the text files with SAP BODS 3.2

    Hello
    I can not edit some text files 9-20 megabytes to replace two words in each file, the source is a text file and the same destination but with different name, because with the same name have been unable . My idea is to remove the original and stay with the new performing edition but that if he does , let me file this way:
    SALES_ORDERS_FULL_20140223_150051_006.xml ( ORIGINAL )
    should leave it with me so : SALES_ORDERS_FULL_20140223_150051_006.xml _OLD (AMENDED )
    but strangely leaves me so :
    MICROSOFT_SQL_SERVER_KCC-BI_REPO_KHSA_XI_REPO_KHSA_XI_1543_5434_2_3_Long_INVOICES_INCREMENTAL_20140225_034004_001_xml_dat.txt  (not deseased)
    The type of data you use is long since varchar not allow me because it cuts my data file , use varchar (50000000) but takes the information and short .
    I am using long data type , modify the file and I pass the name of the text files of sap bods for global variables. They are a series of files that are called by a while loop
    Thanks for your answers
    regards

    HIr
    Yes, first I convert long_to_varchar for edit, and convert varchar_to_long.
    I edit before before and later
    Thanks

  • Reading words from a text file

    I have written code to store words in a text file. they appear in the text file as shown below.
    word1
    word2
    word3
    etc.
    I want to read each word individually and store them in an array. Im trying to do it using a BufferedReader but it doesn't seem to work. The code for reading the words is shown below. Any suggestions would be appreciated.
    try
    FileReader reader = new FileReader("words.txt");
    BufferedReader bReader = new BufferedReader(reader);
    ArrayList words = new ArrayList();
    String line;
    while((line = bReader.readLine()) != null)
    line = bReader.readLine();
    words.add(line);
    bReader.close();
    catch (Exception e)
    System.err.println ("Error writing to file");
    }

    I think your code is wrong, because it Read two time from file,
    your code like....
    while((line = bReader.readLine()) != null)
    line = bReader.readLine();
    words.add(line);
    you have to change the above code like
    while((line = bReader.readLine()) != null)
    words.add(line);
    NOW ITS WORKING FINE,...........

Maybe you are looking for

  • Can we have a Real batch process

    The current batch process functionality in Audition records not keystrokes, but settings; so if you record a process using the ClickPop Eliminator functionality under Restoration, you get whatever settings you used with the sound sample you used duri

  • My ipod touch is not syncing new music from my itunes.

    my ipod touch is not syncing new musid from my itunes. when i click on my ipod it only shows one song.

  • Regarding Configuration of Change Request Management in solution manager4.0

    HI Techies, I have configured the change request in solman 4.0 but the transactions SDCR,SDMN,SDMI,SDAD,SDDV,SDTM,SLFN,SDHFare not working for activating this i have executed the BC sets as mentioned in Note :903527 ,is there any BC sets available fo

  • Firefox with Facebook Grandpoker crashes my Windows 7 PC

    Starting about 8 hours ago the Facebook Grandpoker app, when run under Firefox 10.0 crashes my PC. It doesn't just crash Firefox, it gives me the blue screen of death. I've switched rendering engines on the tab with Facebook Grandpoker and don't have

  • Wimpy rave player integrated in iWeb

    TIP: to use a Wimpy 'Rave' Player in iWeb on a (non.dot.mac)server. http://www.wimpyplayer.com are professional mp3/flash/video players with many programmable options and you can use it in your iWebsite. First read and do the Wimpy instructions and i