0

I've a text file which has values given as =

FORMNAME1=Cat
CONTROL ID=6
DATA WIDTH=20
LABEL WIDTH = 30
LABEL ALIGN = R


FORMNAME2= bat
CONTROL ID=5
DATA WIDTH=20
LABEL WIDTH = 30
LABEL ALIGN = R


FORMNAME3= rat
CONTROL_ID3=10
DATAWIDTH3=20
LABELWIDTH3 = 30
LABEL_ALIGN3 = R

How to read only the values stored in each line i.e only the data after = using JAVA?

1 Answers1

2

Read the file as shown here, and use String.split() in each line to get the value:

try (BufferedReader br = new BufferedReader(new FileReader(file))) {
    String line;
    while ((line = br.readLine()) != null) {
        String value = line.split("=")[1];
        System.out.println(value);
    }
}

EXPLANATION: to read the file, is well explained in question I linked

lets see: you are processing each line of the file INDIVIDUALLY, then the content of the file (just one line) arrives to this part of the code, but what is doing this line?

String value = line.split("=")[1];

line variable, in first iteration will contain:

FORMNAME1=Cat

split("=") will create an array like this

[0] FORMNAME1
[1] Cat

so the line is assigning the value of position 1 (Cat) to the variable value

String value = "Cat";

Second iteration will do same but different content:

line = "CONTROL ID=6"

so

line.split("=")

will result

[0] CONTROL ID
[1] 6

And

// be careful is a string representing "6" 
// not the numerical value 6 as int or double!!!!!
String value = "6";  

and so on....


EXTRA TIP:

Community
  • 1
  • 1
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
  • Can you please elaborate on the code as I'm a beginner to Java?? How would I take the values out, can a simple sys out will do?? – Nikhil Sashi Feb 26 '16 at 13:15
  • If you want to print the values `System.out.println(value);` will do the job, but value variable contains the value of the line youre processing. – Jordi Castilla Feb 26 '16 at 13:18
  • @NikhilSashi please, kindly check my update in the answer and let me know if the explanation suits you. Please, **don't hesitate to ask further** if you don't understand some piece or whatever – Jordi Castilla Feb 26 '16 at 14:03
  • @NikhilSashi glad to help. As I can see in your [question record](http://stackoverflow.com/users/5743141/nikhil-sashi?tab=questions) you have not accepted any as answered, You must know if this or any answer has solved your question please consider [accepting it](http://meta.stackexchange.com/q/5234/179419) by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this. – Jordi Castilla Feb 29 '16 at 11:25