Java cgi näide: datafailist htmli tegemine
Allikas: Lambda
list.cgi pathid tuleb muidugi ära muuta, siin toodud töötasid Taneli läpakas. Samuti peaks lõpuks olema üks rida, mitte kaks:
#!/bin/sh cd /tmp /usr/local/java/j2sdk1.4.2_02/bin/java -cp /home/tanel/Ms/SEATS/trunk/www/Katse list $QUERY_STRING
data.txt oli selline:
http://www.itcollege.ee,itk,10,2,1 http://www.epl.ee,epl,5,3,2
ning lõpuks java programm list.java:
import java.io.*;
public class list {
public static void main(String[] args) {
String ls_str;
String filename;
String[] pieces;
int nr=1;
System.out.println("content-type: text/html");
System.out.println("");
System.out.println("<p>Head lingid:</p><p></p>");
//System.out.println(args[0]);
filename="/home/tanel/Ms/SEATS/trunk/www/Katse/data.txt";
File file = new File(filename);
// All file I/O operations must be done within a try/catch statement
try {
// Set up the proper readers and writers
FileReader file_reader = new FileReader(filename);
BufferedReader br_reader = new BufferedReader(file_reader);
// Get the first line of the file
String line = br_reader.readLine();
// check to see if it is null - end of file
while (line != null) {
// print line to output file
//System.out.println(line);
pieces=split(line);
if (pieces.length>1) {
System.out.println(nr+". ");
System.out.println(
"<a href=\""+pieces[0]+"\">"+
pieces[1]+
"</a>");
System.out.println(pieces[2]+"+ ja "+
pieces[3]+"-");
System.out.println("<br>");
nr++;
}
// get next line of input file
line = br_reader.readLine();
} // while loop
// Finally you must close input and output streams!
file_reader.close();
} //try
// catch any exceptions thrown
catch (IOException e) {
//print error and exit program
System.out.println(e);
System.exit(1);
}
}
public static String[] split(String input) {
int len;
int count;
int pos;
String separator=",";
int ws;
int we;
String[] words;
/* count the number of separators:
then we know the required size of the array */
len=input.length();
count=0;
pos=-1;
for(;;) { // loop over all occurrences of separator in input
pos=input.indexOf(separator,pos+1); // search from last pos found!
if (pos<0) break; // none found after pos
count++;
}
// let us print some useful debug information
//System.out.println("\nFound "+count+" separators "+separator);
// make a suitable array
words=new String[count+1];
// loop again over the input, this time collecting strings
ws=0; // word start
we=ws+1; // word end
count=0;
pos=-1;
for(;;) { // again, loop over all occurrences of separator in input
pos=input.indexOf(separator,pos+1); // search from last pos found!
if (pos<0) {
// no separator found after pos: take to end of string
we=input.length();
} else {
// separator found
we=pos;
}
words[count]=input.substring(ws,we).trim(); // take substring, remove spaces
ws=pos+separator.length(); // this is where the next word will start
count++;
if (pos<0) break;
}
return words;
}
}