Aniq
Aniq

Reputation: 205

I/O file reading issue in java

I have a file in which assembly language is written MOV R1,1, now what I have to do is that I have to Read it like e.g

First it should scan MOV,

Then R1,

then 1.`

But when I use input.next(), it scans like

Mov

then R1,1

What should I do?

Upvotes: 0

Views: 63

Answers (3)

Aleksander Mielczarek
Aleksander Mielczarek

Reputation: 2825

Solution with Java8 and streams:

try (BufferedReader bufferedReader = new BufferedReader(new FileReader("f.txt"))) {
    List<String> words = bufferedReader.lines()
            .map(line -> line.split("[\\s,]"))
            .flatMap(Arrays::stream)
            .collect(Collectors.toList());
} catch (IOException e) {
    e.printStackTrace();
}

Upvotes: 0

adrCoder
adrCoder

Reputation: 3285

You may use the *String.split()* method to split the tokens that have commas:

String[] ar=str.split(",");

After that, get the two values.

string part1 = ar[0];
double part2 = ar[1];

In this case R1 will be stored in part1

Here is a working example for you:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;

public class BufferedReaderExample {

    public static void main(String[] args) {

try (BufferedReader br = new BufferedReader(new FileReader("testing.txt")))
        {

            String sCurrentLine;

            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
                String[] parts = sCurrentLine.split(" ");
                System.out.println(Arrays.toString(parts));
                List<String> splitNames = new ArrayList<>();
                for (String name : parts) {
                splitNames.addAll(Arrays.asList(name.split(",")));
            }
                for (String splitName : splitNames) {
                     System.out.println(splitName);
               }
         }
        } catch (IOException e) {
            e.printStackTrace();
        } 

    }
}

testing.txt contains:

MOV R1,1

OUTPUT :

MOV R1,1
[MOV, R1,1]
MOV
R1
1

As you can see what the code is doing is: For every line split the parts by spaces

String[] parts = sCurrentLine.split(" ");

(This will get you MOV and R1,1)

Then you want to split the tokens you got by the commas:

splitNames.addAll(Arrays.asList(name.split(",")));

Then you are good to go because you have your tokens separated by commas etc, as you want them:

MOV
R1
1

Upvotes: 1

Mordechai
Mordechai

Reputation: 16302

The default delimiter in most streams are "space". Although some allow you to change them by a useDelimiter(...) method. Take a look in the JavaDoc, of your specific stream.

Upvotes: 0

Related Questions