GuestUser140561
GuestUser140561

Reputation: 67

Reading text file that has specific format

I was looking for some help on how to read a text file that has a specific format, and assign them to variables within my program.

TextFile.txt

//Variables
start={x}
forward={c}
end={y}
pause={p}
path={x, c, c, c, c, p, c, c, y}

Class.java

public void readFile()
{

char start, forward, end, pause; 

BufferedReader reader = 
    new BufferedReader (
        new InputStreamReader (new FileInputStream (TextFile.txt)));

String line;
while ((line = reader.readLine ()) != null)
{
    if (line.startWith ("//") || line.trim ().isEmpty ())
        continue; // Ignore the line

    //**This is the part I need help with**
}
}

Could somebody please explain how I could assign the values to the variables from the text file?

So for example, start would equal 'x', forward would equal 'c', etc.

Thanks.

Upvotes: 0

Views: 1321

Answers (2)

Hannes
Hannes

Reputation: 482

You could use something like this:

String line;
while ((line = reader.readLine()) != null) {
    if (line.startsWith("//") || line.trim().isEmpty())
        continue;
    else if(line.startsWith("start"))
        start= line.charAt(line.indexOf("{")+1);
    else if(line.startsWith("forward"))
        forward= line.charAt(line.indexOf("{")+1);
    else if(line.startsWith("end"))
        end= line.charAt(line.indexOf("{")+1);
    else if(line.startsWith("pause"))
        pause= line.charAt(line.indexOf("{")+1);
    else if(line.startsWith("path"))
        for(String s: line.substring(line.indexOf("{")+1, line.indexOf("}")).split(", "))
                path.add(s.charAt(0));

This assumes that your path is defined as LinkedList<Character> path = new LinkedList<>();.

Upvotes: 1

Deepesh Choudhary
Deepesh Choudhary

Reputation: 677

Add this in the class:

java.util.Properties p = new java.util.Properties();

Add this to your code in the while loop after the if statement:

int index = line.indexOf("=");
String var = line.substring(0, index);
int s1 = line.indexOf("{");
int s2 = line.indexOf("}");
String value = line.substring(s1, s2);
p.setProperty(var, value);

In the above code, var is your variable and value is the value of var.

You can further process value to check if it contains , (comma) and if it contains, make a linkedList out of it.

Upvotes: 1

Related Questions