source: josm/src/org/openstreetmap/josm/io/RawCsvReader.java@ 74

Last change on this file since 74 was 74, checked in by imi, 18 years ago

changed Preferences system to more flexible one.

File size: 2.5 KB
Line 
1package org.openstreetmap.josm.io;
2
3import java.io.BufferedReader;
4import java.io.IOException;
5import java.io.Reader;
6import java.util.ArrayList;
7import java.util.Collection;
8import java.util.LinkedList;
9import java.util.StringTokenizer;
10
11import org.jdom.JDOMException;
12import org.openstreetmap.josm.Main;
13import org.openstreetmap.josm.data.coor.LatLon;
14
15/**
16 * Read raw information from a csv style file (as defined in the preferences).
17 * @author imi
18 */
19public class RawCsvReader {
20
21 /**
22 * Reader to read the input from.
23 */
24 private BufferedReader in;
25
26 public RawCsvReader(Reader in) {
27 this.in = new BufferedReader(in);
28 }
29
30 public Collection<LatLon> parse() throws JDOMException, IOException {
31 Collection<LatLon> data = new LinkedList<LatLon>();
32 String formatStr = Main.pref.get("csvImportString");
33 if (formatStr == null)
34 formatStr = in.readLine();
35 if (formatStr == null)
36 throw new JDOMException("Could not detect data format string.");
37
38 // get delimiter
39 String delim = ",";
40 for (int i = 0; i < formatStr.length(); ++i) {
41 if (!Character.isLetterOrDigit(formatStr.charAt(i))) {
42 delim = ""+formatStr.charAt(i);
43 break;
44 }
45 }
46
47 // convert format string
48 ArrayList<String> format = new ArrayList<String>();
49 for (StringTokenizer st = new StringTokenizer(formatStr, delim); st.hasMoreTokens();)
50 format.add(st.nextToken());
51
52 // test for completness
53 if (!format.contains("lat") || !format.contains("lon")) {
54 if (Main.pref.get("csvImportString").equals(""))
55 throw new JDOMException("Format string in data is incomplete or not found. Try setting an manual format string in Preferences.");
56 throw new JDOMException("Format string is incomplete. Need at least 'lat' and 'lon' specification");
57 }
58
59 int lineNo = 0;
60 try {
61 for (String line = in.readLine(); line != null; line = in.readLine()) {
62 lineNo++;
63 StringTokenizer st = new StringTokenizer(line, delim);
64 double lat = 0, lon = 0;
65 for (String token : format) {
66 if (token.equals("lat"))
67 lat = Double.parseDouble(st.nextToken());
68 else if (token.equals("lon"))
69 lon = Double.parseDouble(st.nextToken());
70 else if (token.equals("ignore"))
71 st.nextToken();
72 else
73 throw new JDOMException("Unknown data type: '"+token+"'."+(Main.pref.get("csvImportString").equals("") ? " Maybe add an format string in preferences." : ""));
74 }
75 data.add(new LatLon(lat, lon));
76 }
77 } catch (RuntimeException e) {
78 throw new JDOMException("Parsing error in line "+lineNo, e);
79 }
80 return data;
81 }
82}
Note: See TracBrowser for help on using the repository browser.