Ibz
Ibz

Reputation: 11

reading from file in java

I am reading from a file using this code:

BufferedReader in = new BufferedReader(new FileReader("example.txt"));


      String line;
 while((line = in.readLine()) != null)
{
         String k = line;
        System.out.println(k);
 }
in.close();

This works perfectly fine.. However my text file contains "1. Hello 2. Bye 3. Seeya".. How can i modify my code so that "1. Hello" stores in a variable.. "2. Bye" stores in a different variable.. and so on Thanks in advance!

Upvotes: 1

Views: 91

Answers (2)

user3437460
user3437460

Reputation: 17454

This is how you can do it..

Since the data is in separate lines, it is very straight forward. You can simply use an arrayList to receive the data.

ArrayList can "grow" and "shrink" as needed. Unlike arrays which has fixed size.

 public static void main(String[] args) throws FileNotFoundException
 {
      List<String> record = new ArrayList<String>();     //Use arraylist to store data
      Scanner fScn = new Scanner(new File(“Data.txt”));
      String data;

      while( fScn.hasNextLine() ){
           data = fScn.nextLine();
           record.add(data);   //Add line of text to the array list
      }
      fScn.close();
 }

To retrieve your records from your arraylist, you can simply use a for-loop or for-each loop.

for(int x=0; x<record.size(); x++)
    System.out.println(record.get(x));  

//Get specific record with .get(x) where x is the element id starting from 0. 
//0 means the first element in your arraylist.

Upvotes: 0

Maroun
Maroun

Reputation: 95958

If it's one line, you can use the following:

s.split("(?<=\\w)\\s"));

Since split accepts a regex, you can split according to space that was preceded by a character.

Quick example:

public static void main(String[] args) {
    String s = "1. Hello 2. Bye 3. Seeya";
    System.out.println(Arrays.deepToString(s.split("(?<=\\w)\\s")));
}

Output:

[1. Hello, 2. Bye, 3. Seeya]

If you're referring multiple lines, you can simply loop on the lines and add each one to an ArrayList.

If your input can contain one or more strings on each number bullet, you should use \\s(?=\\d+[.]) which is a space followed by number and a dot - thanks @pshemo

Upvotes: 1

Related Questions