1

I have a txt file like this which contains longitude and latitude coords:

120.12    22.233
100    23.12
98     19.12

If I want to read the file, I am doing:

List<String> lines = Files.readAllLines(Paths.get(fileName));
System.out.println("LINE: " + lines.get(0));

and it gives me : 120 22

I have a class that reads latitude and longitude:

public class GisPoints {

    private double lat;
    private double lon;

    public GisPoints() {
    }

    public GisPoints(double lat, double lon) {
       super();
       this.lat = lat;
       this.lon = lon;
    }

    //Getters and Setters
}

I want to store all the values from the txt file into an List<GisPoints>.

So, I want a function in order to load file:

public static List<GisPoints> loadData(String fileName) throws IOException {

      List<String> lines = Files.readAllLines(Paths.get(fileName));

      List<GisPoints> points = new ArrayList<GisPoints>();

      //for (int i = 0; i < lines.size(); i++) {

     // }

      return points;

  }

As I said, right now I am just reading every line, for example lines[0] = 120 22

I want to store lines[0] longitude into points[0].setLon(), lines[0] latitude into points[0].setLat().

7
  • 1
    String#split Commented Jul 26, 2017 at 9:04
  • what have you tried already? Commented Jul 26, 2017 at 9:04
  • since your file contains only ints, you can use nextInt method in Scanner class Commented Jul 26, 2017 at 9:06
  • @AhmadAlsanie:It will not contain only ints Commented Jul 26, 2017 at 9:07
  • 1
    @AhmadAlsanie Why OP need scanner as he already read the file and got lines ? I didn't understand what you mean. Commented Jul 26, 2017 at 9:09

8 Answers 8

2

This is an easy solution with String.split()

private GisPoints createGisPointsObjectFromLine(String p_line)
{
    String[] split = p_line.trim().split(" ");
    double lat = Double.parseDouble(split[0]);
    double lon = Double.parseDouble(split[split.length - 1]);
    return GisPoints(lat, lon);
}

You can call this method from your loadData() method. I hope this solution is helpful. Good luck!

Sign up to request clarification or add additional context in comments.

Comments

1

It would look like this:

    for (int i = 0; i < lines.size(); i++)
    {
        String line = lines.get(i);

        String[] values = line.split("\\s+");

        double lat = Double.parseDouble(values[0]);
        double lon = Double.parseDouble(values[1]);

        points.add(new GisPoints(lat, lon));
    }

4 Comments

It shows: java.lang.NumberFormatException: For input string: "-117.1".I am trying to use -117.1 32.533
Now, if I print points, it gives me the package name mylib.gispoint.GisPoints@262a8f13, mylib.gispoints.GisPoints@22150f0e,....
@George you have to override the toString() method in your GisPoints class
@George Or get the values through the getter-methods in GisPoint and print it then.
1

I think split can solve your problem:

String arr[] = lines[i].split("\\s+");
GisPoints p = new GisPoints(Double.parseDouble(arr[0]), Double.parseDouble(arr[1]));

1 Comment

arr[0] is String. Not double.
1

I want to store lines[0] longitude into points[0].setLon(), lines[0] latitude into points[0].setLat().

You don't need setters right away. You have a good constructor to receive both of them already.

Just create an object after splitting like into two parts.

 for (int i = 0; i < lines.size(); i++) { 
      String[] latlang = lines.get(i).split("\\s+");
      GisPoints g = new GisPoints(Double.parseDouble(latlang[0].trim()),Double.parseDouble(latlang[1].trim()));
      points.add(g)
    }

2 Comments

you forgot the splitting i guess :)
@SomeJavaGuy Oh no. You saved me :D
1
for (String str : lines) {
    String[] helpArray = str.split("\\s+"); // or whatever is betweeen
                                            // the two numbers
    points.add(new GisPoints(Double.valueOf(helpArray[0].trim()), Double.valueOf(helpArray[1].trim())));
}

this should work as you need it. only works as long as there are only numbers in the file. you can report back if you need further help

Comments

1

You might want to do it with java8-streams:

 List<GisPoint> points = lines.stream()
        .map(s -> s.split("\\s+"))
        .map(array -> Arrays.stream(array)
            .map(String::trim)
            .filter(s -> !s.isEmpty())
            .mapToDouble(Double::parseDouble)
            .toArray()
        )
        .map(array -> new GisPoint(array[0], array[1]))
        .collect(Collectors.toList());

8 Comments

you should .trim() the array values
@XtremeBaumer what about now?
@Lino:It shows java.lang.NumberFormatException: For input string: "-117.1 32.5333333333333", if I use these numbers in the file
@Lino:yes, i have
you have 1 string with 2 numbers which can never be converted. try splitting with \\s+
|
0

Take a look at the class Scanner; Scanner has a lot of useful tools for reading and parsing strings.

3 Comments

This is a good suggestion, but not a complete answer. This would be best as a comment (of course if you intend to improve it that's alright I guess)
You can add some code snippet useful to OP ..else it should be a comment
I must have 50 reputation to comment on questions, which i don't. This is an assignment i think he or she could figure out by himself and thereby i didn't elaborate more, merely pointed him or her in the right direction. Rest assured, if i had 50 rep this would have been simply a comment :-)
0

Take a look with regex :

import java.util.regex.*;

public class HelloWorld{

     public static void main(String []args){
        String line = "98 19";
        Pattern pattern = Pattern.compile("^(\\d+)\\s*(\\d+)$");
        Matcher matcher = pattern.matcher(line);
        while (matcher.find()) {
            System.out.println("group 1: " + matcher.group(1));
            System.out.println("group 2: " + matcher.group(2));
        }
     }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.