How can I read only a line of text from a file, line by line using Scanner?

Here's the code I currently have for a program that finds a keyword from numerous files and prints every line in every file that has that keyword. The keyword is indicated by the first parameter in a command line and the files are every parameter after that. Right now, with the code I have, the program will not print multiple lines of each file if they contain the keyword. I am trying to solve this problem by figuring out a way to have a loop continue until an \n EOL character is found. I am not sure how to do this though. Here's the portion of code that I would like to change to do this. I need to add a condition somewhere after in.hasNext() I think to stop when it it hits a /n.:
while (in.hasNext()) {
                    count++;
                    String nextWord = in.next();
                    lineOfText.add(nextWord);
                    if (nextWord.equals(keyword)) {
                        flag = true;
import java.util.Scanner;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
public class Find {
    static ArrayList<String> lineOfText = new ArrayList<String>();
    static boolean flag = false;
    public static void main(String args[]) {
               run(args);
    public static void run(String args[]) {
        try {
            PrintWriter out = new PrintWriter("output.txt");
            String keyword = args[0];
            for (int i = 1; i < args.length; i++) {
                Scanner in = new Scanner(new FileInputStream(args));
int count = 0;
while (in.hasNext()) {
count++;
String nextWord = in.next();
lineOfText.add(nextWord);
if (nextWord.equals(keyword)) {
flag = true;
if (flag == true) {
System.out.print(args[i] + ": " );
out.print(args[i] + ": " );
for (String s : lineOfText) {
System.out.print(s + " ");
out.print(s + " ");
System.out.print("\n");
out.println(" ");
lineOfText.clear();
out.close();
catch (FileNotFoundException e) {
System.out.println("file not found!");
catch (IOException e) {
System.out.println(e);
Thanks

Well, I thought I had this program finished, then I realized I need to match the keyword anywhere in the file(including within a word) and print out each line that "contains" the keyword in each file. So, I need some way of testing to see if the keyword is a part of each word and then flag the line that contains the keyword. Is there some method to do this? Thanks
Here's the code I have now:
import java.util.Scanner;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.FileInputStream;
import java.io.PrintWriter;
public class Find {
    static String line = "";
    static boolean flag = false;
    static boolean flag2 = false;
    public static void main(String args[]) {
                run(args);
    public static void run(String args[]) {
        try {
            PrintWriter out = new PrintWriter("output.txt");
            String keyword = args[0];
            System.out.print("Searching for the keyword: " + keyword);
            out.print("Searching for the keyword: " + keyword);
            System.out.print("  in files: ");
            out.print("  in files: ");
            for (int k = 1; k < args.length; k++)
                 System.out.print(args[k] + " ");
                 out.print(args[k] + " ");
                 System.out.println("\n");
                 out.println("");
                 out.println("");
            for (int i = 1; i < args.length; i++) {
                Scanner in = new Scanner(new FileInputStream(args));
while (in.hasNextLine()) {
line = in.nextLine();
String[] splitLine = line.split(" ");
for (int j=0; j < splitLine.length; j++) {
if (splitLine[j].equals(keyword) && flag2 == false) {
flag = true;
flag2 = true;
System.out.print(args[i] + ": " + line + "\n");
out.println(args[i] + ": " + line);
flag2 = false;
System.out.print("\n");
out.println(" ");
out.close();
catch (FileNotFoundException e) {
System.out.println("file not found!");
catch (IOException e) {
System.out.println(e);

Similar Messages

  • How can I read only text files in a directory.

    I've written a program to read files in a directory but I'd like for it to only read the text files of that directory.
    import java.io.*;
    public class Data {
      public static void main(String[] args) throws IOException {
      String target_dir = "C:\\files";
      File dir = new File(target_dir);
      File[] files = dir.listFiles();
      for (File textfiles : files) {
      if (textfiles.isFile()) {
      BufferedReader inputStream = null;
      try {
      inputStream = new BufferedReader(new FileReader(textfiles));
      String line;
      while ((line = inputStream.readLine()) != null) {
      System.out.println(line);
      } finally {
      if (inputStream != null) {
      inputStream.close();

    You have mentioned you want to read only text files.
    If you are referring to some specific set of extentions, you can filter based on that.
    ex: you want to read only .txt files, you can add an if condition as below :
              if(textfiles.getName().endsWith(".txt")) {
                  // Add your code here
    Cheers
    AJ

  • Can a read-only snapshot site be refreshed from a read-only database?

    Hi,
    Here is the database configuration.
    Database 1: master site
    Database 2: has materialized views (read-only snapshot site)
    If DB1 becomes read-only, is it possible to refresh the materialized views in DB2? I was told that it is not possible because some m$log tables in DB1 need to be updated when the DB2 is refreshed . If it is DB1 is read-only, the meta data tables can not be updated so the refresh will fail.
    Does anybody have experience with a scenario like this?
    Thanks very much.

    Why do you need to put the database in read only mode anyway. Why not control "readability" through security, ie roles. Then it won't really matter.

  • How can I read, millions of records and write as *.csv file

    I have to return some set of columns values(based on current date) from the database (could be million of record also) The dbms_output can accomodate only 20000 records. (I am retrieving thru a procedure using cursor).
    I should write these values to a file with extn .csv (comma separated file) I thought of using a utl_file. But I heard there is some restriction on the number of records even in utl_file.
    If so, what is the restriction. Is there any other way I can achive it? (BLOB or CLOB ??).
    Please help me in solving this problem.
    I have to write to .csv file, the values from the cursor I have concatinated with "," and now its returning the value to the screen (using dbms_output, temporarily) I have to redirect the output to .csv
    and the .csv should be in some physical directory and I have to upload(ftp) the file from the directory to the website.
    Please help me out.

    Jimmy,
    Make sure that utl_file is properly installed, make sure that the utl_file_dir parameter is set in the init.ora file and that the database has been re-started so that it will take effect, make sure that you have sufficient privileges granted directly, not through roles, including privileges to the file and directory that you are trying to write to, add the exception block below to your procedure to narrow down the source of the exception, then test again. If you still get an error, please post a cut and paste of the exact code that you run and any messages that you received.
    exception
        when utl_file.invalid_path then
            raise_application_error(-20001,
           'INVALID_PATH: File location or filename was invalid.');
        when utl_file.invalid_mode then
            raise_application_error(-20002,
          'INVALID_MODE: The open_mode parameter in FOPEN was
           invalid.');
        when utl_file.invalid_filehandle then
            raise_application_error(-20002,
            'INVALID_FILEHANDLE: The file handle was invalid.');
        when utl_file.invalid_operation then
            raise_application_error(-20003,
           'INVALID_OPERATION: The file could not be opened or
            operated on as requested.');
        when utl_file.read_error then
            raise_application_error(-20004,
           'READ_ERROR: An operating system error occurred during
            the read operation.');
        when utl_file.write_error then
            raise_application_error(-20005,
                'WRITE_ERROR: An operating system error occurred
                 during the write operation.');
        when utl_file.internal_error then
            raise_application_error(-20006,
                'INTERNAL_ERROR: An unspecified error in PL/SQL.');

  • How to populate read only input field or text view form value help only

    Hi experts,
    I have one requirement to populate a read-only field or text view from value help.
    User cant put any value there.value comes only from the value help.
    For example,
    when we read context using Code Wizard,we cant type any value there.value only comes from value help.
    How to implement that functionality?
    Please reply.
    Thanks in advance,
    Subhasis.

    Yes it is possible.
    1.Create a context Attribute and then bind this attribute to the Text view UI element.
    2. read context attribute and then set value to the context attribute like this way.
    DATA:
        elem_context1                        TYPE REF TO if_wd_context_element,
        stru_context1                        TYPE if_first=>element_context ,
        item_potxt                          LIKE stru_context-potxt.
    get element via lead selection
      elem_context1 = wd_context->get_element(  ).
    stru_context1-potxt = 'PO'.
    elem_context1->set_attribute(
        VALUE  = stru_context1
        name   = 'POTXT'
    thanks
    Suman
    Edited by: suman kumar chinnam on Sep 9, 2008 12:12 PM

  • How can I get firefox to execute perl scripts from local files

    I have created perl scripts on my local host (file type ".pl").
    In MS Windows I have associated that type to a perl interpreter installed on my local host.
    IE allows me to create links to them and to execute them (after asking for permission).
    How can I get firefox to do the same? It doesn't seem to allow me to add application types, only to change those that are already defined. As a result, in firefox, they just show up as text, instead of being executed.

    First guess is that you did not use an .html extension on the file. The file may well be ''name.html.txt''
    * see http://www.bbc.co.uk/webwise/guides/file-extensions
    *http://windows.microsoft.com/en-gb/windows/show-hide-file-name-extensions#show-hide-file-name-extensions=windows-vista
    Forum Note
    This is normally offtopic for this forum. I say normally because now we cover webmaker questions. I wonder if this is therefore on topic as a webmaker question?
    I have tagged with webmaker-contribution

  • How can I change the size of the letter (from medium to large) that is used in my HTML signature?

    I've written my HTML signature in code. Afterwards, I decided to change my standard letter size from medium to large (about 10 point to 11.5 point I think). However, my signature remains the old size. How can I get my signature to have the same letter size as the rest of my text?

    Hello,
    Maybe help:
    *[http://academe.co.uk/2012/03/creating-an-html-signature-in-mozilla-thunderbird/]

  • How can i remove a key and its value from properties file

    hi all,
    i want remove a particular key and associated value from the
    properties file. is their any standard way of doing?
    thanks inadvance
    daya

    hi,
    thanks
    i am able to remove the key,
    one more question how can avoid storing date and time
    in properties file.
    thanks
    daya

  • How can i read all the lines from a text file in specific places and use the data ?

    string[] lines = File.ReadAllLines(@"c:\wmiclasses\wmiclasses1.txt");
    for (int i = 0; i < lines.Length; i++)
    if (lines[i].StartsWith("ComboBox"))
    And this is how the text file content look like:
    ComboBox Name cmbxOption
    Classes Win32_1394Controller
    Classes Win32_1394ControllerDevice
    ComboBox Name cmbxStorage
    Classes Win32_LogicalFileSecuritySetting
    Classes Win32_TapeDrive
    What i need to do is some things:
    1. Each time the line start with ComboBox then to get only the ComboBox name from the line for example cmbxOption.
       Since i have already this ComboBoxes in my form1 designer i need to identify where the cmbxOption start and end and when the next ComboBox start cmbxStorage.
    2. To get all the lines of the current ComboBox for example this lines belong to cmbxOption:
    Classes Win32_1394Controller
    Classes Win32_1394ControllerDevice
    3. To create from each line a Key and Value for example from the line:
    Classes Win32_1394Controller
    Then the key will be Win32_1394Controller and the value will be only 1394Controller
    Then the second line key Win32_1394ControllerDevice and value only 1394ControllerDevice
    4. To add to the correct belonging ComboBox only the value 1394Controller.
    5. To make that when i select in the ComboBox for example in cmbxOption the item 1394Controller it will act like i selected Win32_1394Controller.
    For example in this event:
    private void cmbxOption_SelectedIndexChanged(object sender, EventArgs e)
    InsertInfo(cmbxOption.SelectedItem.ToString(), ref lstDisplayHardware, chkHardware.Checked);
    In need that the SelectedItem will be Win32_1394Controller but the user will see in the cmbxOption only 1394Controller without the Win32_
    This is the start of the method InsertInfo
    private void InsertInfo(string Key, ref ListView lst, bool DontInsertNull)
    That's why i need that the Key will be Win32_1394Controller but i want that the user will see in the ComboBox only 1394Controller without the Win32_

    Hello,
    Here is a running start on getting specific lines in the case lines starting with ComboBox. I took your data and placed it into a text file named TextFile1.txt in the bin\debug folder. Code below was done in
    a console app.
    using System;
    using System.IO;
    using System.Linq;
    namespace ConsoleApplication1
    internal class Program
    private static void Main(string[] args)
    var result =
    from T in File.ReadAllLines(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TextFile1.txt"))
    .Select((line, index) => new { Line = line, Index = index })
    .Where((s) => s.Line.StartsWith("ComboBox"))
    select T
    ).ToList();
    if (result.Count > 0)
    foreach (var item in result)
    Console.WriteLine("Line: {0} Data: {1}", item.Index, item.Line);
    Console.ReadLine();
    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my webpage under my profile but do not reply to forum questions.

  • How can i read only .txt file and skip other files in Mail Sender Adapter ?

    Hi Friends ,
                       <b> I am working on scenario like , I have to read an mail attachement and send the data to R3.</b>
                        It is working fine if only the .txt file comes.
                      <b>Some times ,html files also coming along with that .txt files. That time my Mail adapter fails to read the .txt file.</b>
                       I am using PayLoadSwap Bean and MessageTransformBean to swap and send the attachment as payload .
                         <b>Michal as told to write the Adapter module to skip the files .But i am not ware of the adapter moduel . If any blogs is there for this kind of scenarios please give me the link.</b>
                           Otherwise , please tell me how to write adapter module for Mail  Sender Adapter?
                      How to download the following
                        newest patch of XI ADAPTER FRAMEWORK CORE 3.0
    from SAP Service Marketplace. Open the file with WinZip and extract the following
    SDAs:
    &#61589;&#61472;aii_af_lib.sda, aii_af_svc.sda
    &#61589;&#61472;aii_af_cpa_svc.sda
                        I have searche in servive market place .But i couldn't find that . Can you please provide me the link to download the above .
                      If any other suggestions other than this please let me know.
    Regards.,
    V.Rangarajan

    =P
    Dude, netiquette. Messages like "i need this now! Do it!" are really offensive and no one here is being payed to answer anyone's questions. We're here because we like to contribute to the community.
    Anyway, in your case, just perform some search on how you could filter the files that are attached to the message. The sample module is just an example, you'll have to implement your own. Tips would be to query the filename of the attachments (or maybe content type) and for the ones which are not text, remove them.
    Regards,
    Henrique.

  • How can I read without EOI line assert?

    Hi.
    Our machine used ibrd() for read from Tester(another machine).
    but i don't read data from Tester now.
    Tester used Send(....,NULLend)function of GPIB 488.2.
    I know that NULLend is not assert EOI line and don't send new line character.
    But Tester's program can't change source code.
    our machine Tester
    Send(....NULLend)
    * ibrd <-
    * (don't read)
    * (time out)
    * ibrd
    * (read data)
    I want read data from tester without changed Tester's program.
    Any advice????

    Hi,
    You shouldn't have any problems reading from a device that does not assert the EOI line or sends a termination character. When you do a ibrd, the function will wait for the specified timeout period and return with a timeout error and the accepted bytes.
    You'll have to set the timeout value so that you give enough time to the device to transfer all the data. For example, if you do an ibrd for 100 bytes, the timeout is set to 1 second and the instrument send 50 bytes. The ibrd function will return one second later with the 50 received bytes. If the device sends more that 100 bytes, the ibrd function will return inmediatly. You'll probably have to call ibrd again until it times out, since that would be the only garantee that the device send all the da
    ta.
    Hope this helps.
    DiegoF.
    National Instruments.

  • How can we extend the subject line using SO_NEW_DOCUMENT_ATT_SEND_API1??

    Hi,
    I am triggering a mail using the function module SO_NEW_DOCUMENT_ATT_SEND_API1, where in the subject of the mail is passed using the DOC_CHNG-OBJ_DESCR, here the object_descr can only accomadate 50 characters.
    But requirement is to have more than 50 characters may be 100 to 150 in the subject line.Please help me to extend.
    Thanks in advance.

    Hi,
    Searched in the forum for the above requirement but didnt find the required info..
    Please help me in finding a solution to this
    Thanks in advance

  • Qosmio G30: How can I install only Ulead Dvd movie factory from Recovery image

    Hi everybody
    I have question about Ulead dvd movie factory.
    First, I bought my G30 with XP when it was the moment of the offer "vista for a few euros".
    So, I installed Vista with the official CD from Toshiba. But there was no longer Ulead Dvd movie Factory. As the XP's restoration CD is only an image disk, I can't install from it.
    Has anybody a solution for me?
    Thank's.
    BR.

    I think there is a solution!
    I found the Ulead DVD Movie Factory utility on the Toshiba page.
    I searched in the Qosmio G30 area but without to be successful.
    But I checked other sections and selected Satellite Satellite A series Satellite A200 (PSAEC) Vista and found the Ulead DVD Movie Factory 5.51.0147.03 version
    Download it a try to install this tool.
    Should works!

  • How to protect read-only data in Swing app from tampering?

    First off I am new to cryptography and trying to find the best approach for a problem.
    We have a Swing application that uses xml-based template files to display complex forms and validate data entry. Based on the size and complexity of the forms it was deemed better to have a distributed stand-alone application instead of a web-based solution. However, we want to ensure users do not tamper with the template rules in order to pass the validation checks. All of the xml-based template files are distributed within a single jar file.
    The first thought was to build a list of check-sums of the template files and to compare the template to the approariate check-sum from within the list before loading a template. This would prevent the more casual user from tampering with the file but not someone knowledgeable in check-sum who could recalculate the CRC and update the list after making changes.
    Another thought was to use a private key to encrypt the CRC list before distribution and a public key to decrypt it during execution with the keys maintained in a keystore. However, once again, an adventurous user could weed through the obfuscated code to determine the password to the keystore, create a new keystore with the same password and use its private key to regenerate the CRC list from altered templates.
    I feel like there must be a simpler approach that will provide a bullet prove implementation. Any suggestions?

    I think you have to re-think your design.
    Whether you use Java, C#,C or C++ a hacker can look through the binary (class file, exe file etc) and after working out what is happening he can modify your code.
    It is my opinion that your best bet is to use client/server but even with that you cannot keep any private data or code on the client.
    You will still have to think about 'man-in-the-middle' and 'spoof site' attacks.

  • Regular Expressions - How can I read the char of a text using the index?

    Assuming that, this is a findWord function which searches in a text and returns the indexes that a given word is located. How to read the characters that are located some pos before each index?
    Kind regards,
    Vag.
    public static void findWord(String type) {
            int count = 0;
            String regex = "<a word>";
            String text = readFile("data/raw/" + type + "/" + type + ".page.all.txt");
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(text);
            System.out.print("Word <a word> was found at positions");
            while (matcher.find()) {
                count++;
                System.out.print(", " + matcher.start());
            System.out.println(" at a total of " + count + " times!");
        }

    Read the API docs for java.util.regex.Matcher. The matcher object exposes this data via start() and end() methods.

Maybe you are looking for