Because many Program Code JAVA Implementation (JSP), I made a Java version using a little time, I am still getting started in Java, during which I checked some information, although the program is relatively short, but it is still naughty.
As mentioned above, Java is used to obtain the URL content. This technology is used to obtain the content, and then the regular expression matching result is complete. Check the Code:
Copy code The Code is as follows: // javac googletranslator. Java-encoding UTF-8
Import java. Io. inputstream;
Import java.net. urlencoder;
Import java. util. RegEx .*;
Public class googletranslator {
Public String geturlcontent (string path ){
String RTN = "";
Int C;
Try {
Java.net. url l_url = new java.net. URL (PATH );
Java.net. httpurlconnection l_connection = (java.net. httpurlconnection) l_url.openconnection ();
Rochelle connection.setrequestproperty ("User-Agent", "Mozilla/4.0 ");
Rochelle connection.connect ();
Inputstream l_urlstream = l_connection.getinputstream ();
While (C = l_urlstream.read ())! =-1 )){
Int all = l_urlstream.available ();
Byte [] B = new byte [all];
L_urlstream.read (B );
RTN + = new string (B, "UTF-8 ");
}
// Thread. Sleep (2000 );
L_urlstream.close ();
} Catch (exception e ){
E. printstacktrace ();
}
Return RTN;
}
Public String gettext (string SRC ){
String OS = NULL;
Try {
String purl = "http://translate.google.com/translate_t? Langpair = "+ urlencoder. encode (" ZH-CN | En "," UTF-8 ") +" & text = "+ urlencoder. encode (SRC," gb2312 ");
String pagecontent = geturlcontent (purl );
If (! Isnullorempty (pagecontent )){
OS = getmatchstring (pagecontent, "(<Div id = result_box dir = \" LTR \ "> )([? : \ S] *?) </Div> ", 2 );
}
} Catch (exception e ){
E. printstacktrace ();
}
Return OS;
}
Private Boolean isnullorempty (string PARAM ){
Return Param = NULL | Param. Trim (). Length () = 0;
}
Public String getmatchstring (string text, string pattern, int point ){
Pattern P = pattern. Compile (pattern );
Matcher M = P. matcher (text );
If (M. Find ()){
Return M. Group (point); // match 1st items
}
Return NULL;
}
Public static void main (string [] ARGs ){
Googletranslator OBJ = new googletranslator ();
System. Out. println (obj. gettext ("cjjer is a Java genius "));
}
};
Save it as googletranslator. Java and then use:Copy codeThe Code is as follows: javac googletranslator. Java-encoding UTF-8
Compiled, and then Java is enough.