3 import java
.util
.HashMap
;
5 import java
.io
.FileReader
;
6 import java
.io
.IOException
;
7 import java
.io
.InputStream
;
8 import java
.io
.BufferedReader
;
9 import java
.io
.FileInputStream
;
10 import java
.io
.StreamTokenizer
;
11 import java
.io
.BufferedInputStream
;
15 final static long serialVersionUID
= (long)1.0;
17 protected StreamTokenizer streamtokenizer
;
18 protected HashMap
<Integer
, CoordinatePair
<Integer
, Integer
>> coordinates
;
20 TSPLibReader(String filename
) throws IOException
{
21 this(new File(filename
));
24 TSPLibReader(File file
) throws IOException
{
26 new HashMap
<Integer
, CoordinatePair
<Integer
, Integer
>>(countLines(new FileInputStream(file
)));
28 streamtokenizer
= new StreamTokenizer(new BufferedReader(new FileReader(file
)));
29 streamtokenizer
.eolIsSignificant(true);
30 streamtokenizer
.wordChars('_','_');
33 public HashMap
<Integer
, CoordinatePair
<Integer
, Integer
>> getCoordinates() {
36 } catch (IOException e
) {
37 System
.out
.println(e
.toString() + "(" + e
.getClass() + "): " + e
);
43 protected void parseLines() throws IOException
{
45 boolean SeenDisplayDataSection
= false;
46 int i
= 0, x
= 0, y
= 0, City
= 0;
50 if (!SeenDisplayDataSection
) {
51 streamtokenizer
.nextToken();
52 //System.out.println(streamtokenizer);
53 if (streamtokenizer
.ttype
== StreamTokenizer
.TT_WORD
)
54 if (streamtokenizer
.sval
.equals("DISPLAY_DATA_SECTION") ||
55 streamtokenizer
.sval
.equals("NODE_COORD_SECTION"))
56 SeenDisplayDataSection
= true;
61 streamtokenizer
.nextToken();
62 if (streamtokenizer
.ttype
== StreamTokenizer
.TT_NUMBER
) {
69 streamtokenizer
.nextToken();
70 if (streamtokenizer
.ttype
== StreamTokenizer
.TT_NUMBER
) {
71 x
= (int)streamtokenizer
.nval
;
78 streamtokenizer
.nextToken();
79 if (streamtokenizer
.ttype
== StreamTokenizer
.TT_NUMBER
) {
80 y
= (int)streamtokenizer
.nval
;
87 streamtokenizer
.nextToken();
88 if (streamtokenizer
.ttype
== StreamTokenizer
.TT_EOL
&& i
== 3)
89 coordinates
.put(City
++, new CoordinatePair
<Integer
, Integer
>(x
, y
));
93 } while (streamtokenizer
.ttype
!= StreamTokenizer
.TT_EOF
);
97 protected int countLines(FileInputStream fis
) throws IOException
{
98 InputStream is
= new BufferedInputStream(fis
);
99 byte[] c
= new byte[1024];
102 while ((readChars
= is
.read(c
)) != -1) {
103 for (int i
= 0; i
< readChars
; ++i
) {
111 public static void main(String
[] args
) {
113 TSPLibReader tlr
= new TSPLibReader(args
[0]);
115 HashMap
<Integer
, CoordinatePair
<Integer
, Integer
>> coordinates
=
116 tlr
.getCoordinates();
118 System
.out
.println("Entries in HashMap: " + coordinates
.size());
120 for (int k
: coordinates
.keySet())
121 System
.out
.println("City " + k
+ " with Coordinates " +
122 coordinates
.get(k
).getFirst() +
124 coordinates
.get(k
).getSecond());
126 } catch (IOException e
) {
127 System
.out
.println(e
.toString() + "(" + e
.getClass() + "): " + e
);