1 import java
.util
.HashMap
;
3 import java
.io
.FileReader
;
4 import java
.io
.IOException
;
5 import java
.io
.InputStream
;
6 import java
.io
.BufferedReader
;
7 import java
.io
.FileInputStream
;
8 import java
.io
.StreamTokenizer
;
9 import java
.io
.BufferedInputStream
;
13 final static long serialVersionUID
= (long)1.0;
15 protected StreamTokenizer streamtokenizer
;
16 protected HashMap
<Integer
, CoordinatePair
<Integer
, Integer
>> coordinates
;
18 TSPLibReader(String filename
) throws IOException
{
19 this(new File(filename
));
22 TSPLibReader(File file
) throws IOException
{
24 new HashMap
<Integer
, CoordinatePair
<Integer
, Integer
>>(countLines(new FileInputStream(file
)));
26 streamtokenizer
= new StreamTokenizer(new BufferedReader(new FileReader(file
)));
27 streamtokenizer
.eolIsSignificant(true);
28 streamtokenizer
.wordChars('_','_');
31 public HashMap
<Integer
, CoordinatePair
<Integer
, Integer
>> getCoordinates() {
34 } catch (IOException e
) {
35 System
.out
.println(e
.toString() + "(" + e
.getClass() + "): " + e
);
41 protected void parseLines() throws IOException
{
43 boolean SeenDisplayDataSection
= false;
44 int i
= 0, x
= 0, y
= 0, City
= 0;
48 if (!SeenDisplayDataSection
) {
49 streamtokenizer
.nextToken();
50 //System.out.println(streamtokenizer);
51 if (streamtokenizer
.ttype
== StreamTokenizer
.TT_WORD
)
52 if (streamtokenizer
.sval
.equals("DISPLAY_DATA_SECTION") ||
53 streamtokenizer
.sval
.equals("NODE_COORD_SECTION"))
54 SeenDisplayDataSection
= true;
59 streamtokenizer
.nextToken();
60 if (streamtokenizer
.ttype
== StreamTokenizer
.TT_NUMBER
) {
67 streamtokenizer
.nextToken();
68 if (streamtokenizer
.ttype
== StreamTokenizer
.TT_NUMBER
) {
69 x
= (int)streamtokenizer
.nval
;
76 streamtokenizer
.nextToken();
77 if (streamtokenizer
.ttype
== StreamTokenizer
.TT_NUMBER
) {
78 y
= (int)streamtokenizer
.nval
;
85 streamtokenizer
.nextToken();
86 if (streamtokenizer
.ttype
== StreamTokenizer
.TT_EOL
&& i
== 3)
87 coordinates
.put(City
++, new CoordinatePair
<Integer
, Integer
>(x
, y
));
91 } while (streamtokenizer
.ttype
!= StreamTokenizer
.TT_EOF
);
95 protected int countLines(FileInputStream fis
) throws IOException
{
96 InputStream is
= new BufferedInputStream(fis
);
97 byte[] c
= new byte[1024];
100 while ((readChars
= is
.read(c
)) != -1) {
101 for (int i
= 0; i
< readChars
; ++i
) {
109 public static void main(String
[] args
) {
111 TSPLibReader tlr
= new TSPLibReader(args
[0]);
113 HashMap
<Integer
, CoordinatePair
<Integer
, Integer
>> coordinates
=
114 tlr
.getCoordinates();
116 System
.out
.println("Entries in HashMap: " + coordinates
.size());
118 for (int k
: coordinates
.keySet())
119 System
.out
.println("City " + k
+ " with Coordinates " +
120 coordinates
.get(k
).getFirst() +
122 coordinates
.get(k
).getSecond());
124 } catch (IOException e
) {
125 System
.out
.println(e
.toString() + "(" + e
.getClass() + "): " + e
);