namrata shahade
namrata shahade

Reputation: 183

Read the each string text from file in java

I am new in java. I just wants to read each string in java and print it on console.

Code:

public static void main(String[] args) throws Exception {

    File file = new File("/Users/OntologyFile.txt");
    try {
        FileInputStream fstream = new FileInputStream(file);
        BufferedReader infile = new BufferedReader(new InputStreamReader(
                fstream));
        String data = new String();
        while ((data = infile.readLine()) != null) { // use if for reading just 1 line
            System.out.println(""+data);
        }
    } catch (IOException e) {
        // Error
    }
}

If file contains:

Add label abc to xyz
Add instance cdd to pqr

I want to read each word from file and print it to a new line, e.g.

Add
label
abc
...

And afterwards, I want to extract the index of a specific string, for instance get the index of abc.

Can anyone please help me?

Upvotes: 2

Views: 239

Answers (5)

Phanindra Gopishetty
Phanindra Gopishetty

Reputation: 169

      List<String> words = new ArrayList<String>();
       while ((data = infile.readLine()) != null) { 
           for(String d : data.split(" ")) {
             System.out.println(""+d);
           }
           words.addAll(Arrays.asList(data));   
         }
    //words List will hold all the words. Do words.indexOf("abc") to get index


     if(words.indexOf("abc") < 0) {
        System.out.println("word not present");     
      } else {
       System.out.println("word present at index " + words.indexOf("abc"))
      }

Upvotes: 0

Am_I_Helpful
Am_I_Helpful

Reputation: 19158

Just add a for-each loop before printing the output :-

while ((data = infile.readLine()) != null) { // use if for reading just 1 line
  for(String temp : data.split(" "))
  System.out.println(temp); // no need to concatenate the empty string.
}

This will automatically print the individual strings, obtained from each String line read from the file, in a new line.

And afterwards, I want to extract the index of a specific string, for instance get the index of abc.

I don't know what index are you actually talking about. But, if you want to take the index from the individual lines being read, then add a temporary variable with count initialised to 0.

Increment it till d equals abc here. Like,

int count = 0;
for(String temp : data.split(" ")){
 count++;
 if("abc".equals(temp))
  System.out.println("Index of abc is : "+count);
 System.out.println(temp);
}

Upvotes: 1

ifly6
ifly6

Reputation: 5331

Split the String received for any whitespace with the regex \\s+ and print out the resultant data with a for loop.

public static void main(String[] args) {    // Don't make main throw an exception

    File file = new File("/Users/OntologyFile.txt");

    try {
        FileInputStream fstream = new FileInputStream(file);
        BufferedReader infile = new BufferedReader(new InputStreamReader(fstream));

        String data;
        while ((data = infile.readLine()) != null) {
            String[] words = data.split("\\s+");    // Split on whitespace
            for (String word : words) {             // Iterate through info
                System.out.println(word);           // Print it
            }
        }

    } catch (IOException e) {
        // Probably best to actually have this on there
        System.err.println("Error found.");
        e.printStackTrace();
    }
}

Upvotes: 1

Vikrant Kashyap
Vikrant Kashyap

Reputation: 6846

Use Split() Function available in Class String.. You may manipulate according to your need.

or

use length keyword to iterate throughout the complete line and if any non- alphabet character get the substring()and write it to the new line.

Upvotes: 0

Ori Lentz
Ori Lentz

Reputation: 3688

It sounds like you want to be able to do two things:

  1. Print all words inside the file
  2. Search the index of a specific word

In that case, I would suggest scanning all lines, splitting by any whitespace character (space, tab, etc.) and storing in a collection so you can later on search for it. Not the question is - can you have repeats and in that case which index would you like to print? The first? The last? All of them?

Assuming words are unique, you can simply do:

public static void main(String[] args) throws Exception {

    File file = new File("/Users/OntologyFile.txt");
    ArrayList<String> words = new ArrayList<String>();
    try {
        FileInputStream fstream = new FileInputStream(file);
        BufferedReader infile = new BufferedReader(new InputStreamReader(
                fstream));
        String data = null;
        while ((data = infile.readLine()) != null) {
            for (String word : data.split("\\s+") {
                words.add(word);
                System.out.println(word);
            }
        }
    } catch (IOException e) {
        // Error
    }

    // search for the index of abc:
    for (int i = 0; i < words.size(); i++) {
        if (words.get(i).equals("abc")) {
             System.out.println("abc index is " + i);
             break;
        }
    }
}

If you don't break, it'll print every index of abc (if words are not unique). You could of course optimize it more if the set of words is very large, but for a small amount of data, this should suffice.

Of course, if you know in advance which words' indices you'd like to print, you could forego the extra data structure (the ArrayList) and simply print that as you scan the file, unless you want the printings (of words and specific indices) to be separate in output.

Upvotes: 1

Related Questions