Java Reference
In-Depth Information
Because the pattern may extend over more than one line, I read the entire web page from the
File into a String
)
instead of the more traditional line-at-a-time paradigm. I then plot a graph
using an external program (see
Running an External Program from Java
)
; this could (and
should) be changed to use a Java graphics program (see
Program: Grapher
for some leads).
The complete program is shown in
Example 4-10
.
Example 4-10. BookRank.java
public
public class
class
BookRank
BookRank
{
public
public final
final static
static
String DATA_FILE
=
"book.sales"
;
public
public final
final static
static
String GRAPH_FILE
=
"book.png"
;
public
public final
final static
static
String PLOTTER_PROG
=
"/usr/local/bin/gnuplot"
;
final
final static
static
String isbn
=
"0596007019"
;
final
final static
static
String title
=
"Java Cookbook"
;
/** Grab the sales rank off the web page and log it. */
public
public static
static
void
void
main
(
String
[]
args
)
throws
throws
Exception
{
Properties p
=
new
new
Properties
();
p
.
load
(
new
new
FileInputStream
(
args
.
length
==
0
?
"bookrank.properties"
:
args
[
1
]));
String title
=
p
.
getProperty
(
"title"
,
"NO TITLE IN PROPERTIES"
);
// The url must have the "isbn=" at the very end, or otherwise
// be amenable to being string-catted to, like the default.
String url
=
p
.
getProperty
(
"url"
,
"http://test.ing/test.cgi?isbn="
);
// The 10-digit ISBN for the topic.
String isbn
=
p
.
getProperty
(
"isbn"
,
"0000000000"
);
// The RE pattern (MUST have ONE capture group for the number)
String pattern
=
p
.
getProperty
(
"pattern"
,
"Rank: (\\d+)"
);
int
int
rank
=
getBookRank
(
isbn
);
System
.
out
.
println
(
"Rank is "
+
rank
);
// Now try to draw the graph, using external
// plotting program against all historical data.
// Could use gnuplot, R, any other math/graph program.
// Better yet: use one of the Java plotting APIs.
PrintWriter pw
=
new
new
PrintWriter
(
new
new
FileWriter
(
DATA_FILE
,
true
true
));
String date
=
new
new
SimpleDateFormat
(
"MM dd hh mm ss yyyy "
).
format
(
new
new
Date
());