外文翻译java
- 格式:docx
- 大小:35.04 KB
- 文档页数:10
文档从互联网中收集,已重新修正排版,word格式支持编辑,如有帮助欢迎下载支持。
外文翻译原文及译文学院计算机学院专业计算机科学与技术班级学号姓名指导教师负责教师Java(programming language)Java is a general-purpose, concurrent, class-based, object-oriented computer program- -ming language that is specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere" (WORA), meaning that code that runs on one platform does not need to be recompiled to run on another. Java applications are typically compiled to byte code (class file) that can run on any Java virtual machine(JVM) regardless of computer architecture. Java is, as of 2012, one of the most popular programming languages in use, particularly for client-server web applications, with a reported 10 million users. Java was originally developed by James Gosling at Sun Microsystems (which has since merged into Oracle Corporation) and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++, but it has fewer low-level facilities than either of them.The original and reference implementation Java compilers, virtual machines, and class libraries were developed by Sun from 1991 and first released in 1995. As of May 2007, in compliance with the specifications of the Java Community Process, Sun relicensed most of its Java technologies under the GNU General Public License. Others have also developed alternative implementations of these Sun technologies, such as the GNU Compiler for Java and GNU Classpath.Java is a set of several computer software products and specifications from Sun Microsystems (which has since merged with Oracle Corporation), that together provide a system for developing application software and deploying it in across-platform computing environment. Java is used in a wide variety of computing platforms from embedded devices and mobile phones on the low end, to enterprise servers and supercomputers on the high end. While less common, Java appletsare sometimes used to provide improved and secure functions while browsing the World Wide Web on desktop computers.Writing in the Java programming language is the primary way to produce code that will be deployed as Java bytecode. There are, however, byte code compilers available forother languages such as Ada, JavaScript, Python, and Ruby. Several new languages have been designed to run natively on the Java Virtual Machine (JVM), such as Scala, Clojure and Groovy.Java syntax borrows heavily from C and C++, but object-oriented features are modeled after Smalltalk and Objective-C. Java eliminates certain low-level constructs such as pointers and has a very simple memory model where every object is allocated on the heap and all variables of object types are references. Memory management is handled through integrated automatic garbage collection performed by the JVM.An edition of the Java platform is the name for a bundle of related programs from Sun that allow for developing and running programs written in the Java programming language. The platform is not specific to any one processor or operating system, but rather an execution engine (called a virtual machine) and a compiler with a set of libraries that are implemented for various hardware and operating systems so that Java programs can run identically on all of them. The Java platform consists of several programs, each of which provides a portion of its overall capabilities. For example, the Java compiler, which converts Java source code into Java byte code (an intermediate language for the JVM), is provided as part of the Java Development Kit (JDK). The Java Runtime Environment(JRE), complementing the JVM with a just-in-time (JIT) compiler, converts intermediate byte code into native machine code on the fly. An extensive set of libraries are also part of the Java platform.The essential components in the platform are the Java language compiler, the libraries, and the runtime environment in which Java intermediate byte code "executes" according to the rules laid out in the virtual machine specification.In most modern operating systems (OSs), a large body of reusable code is provided to simplify the programmer's job. This code is typically provided as a set of dynamically loadable libraries that applications can call at runtime. Because the Java platform is not dependent on any specific operating system, applications cannot rely on any of the pre-existing OS libraries. Instead, the Java platform provides a comprehensive set of its own standard class libraries containing much of the same reusable functions commonly found in modern operating systems. Most of the system library is also written in Java. For instance, Swing library paints the user interface and handles the events itself, eliminatingmany subtle differences between how different platforms handle even similar components.The Java class libraries serve three purposes within the Java platform. First, like other standard code libraries, the Java libraries provide the programmer a well-known set of functions to perform common tasks, such as maintaining lists of items or performing complex string parsing. Second, the class libraries provide an abstract interface to tasks that would normally depend heavily on the hardware and operating system. Tasks such as network access and file access are often heavily intertwined with the distinctive implementations of each platform. The and java.io libraries implement an abstraction layer in native OS code, then provide a standard interface for the Java applications to perform those tasks. Finally, when some underlying platform does not support all of the features a Java application expects, the class libraries work to gracefully handle the absent components, either by emulation to provide a substitute, or at least by providing a consistent way to check for the presence of a specific feature.The success of Java and its write once, run anywhere concept has led to other similar efforts, notably the .NET Framework, appearing since 2002, which incorporates many of the successful aspects of Java. .NET in its complete form (Microsoft's implementation) is currently only fully available on Windows platforms, whereas Java is fully available on many platforms. .NET was built from the ground-up to support multiple programming languages, while the Java platform was initially built to support only the Java language, although many other languages have been made for JVM since..NET includes a Java-like language called Visual J# (formerly named J++) that is incompatible with the Java specification, and the associated class library mostly dates to the old JDK 1.1 version of the language. For these reasons, it is more a transitional language to switch from Java to the .NET platform, than a first class .NET language. Visual J# was discontinued with the release of Microsoft Visual Studio 2008. The existing version shipping with Visual Studio 2005will be supported until 2015 as per the product life-cycle strategy.In June and July 1994, after three days of brainstorming with John Gage, the Director of Science for Sun, Gosling, Joy, Naughton, Wayne Rosing, and Eric Schmidt, the team re-targeted the platform for the World Wide Web. They felt that with the advent of graphical web browsers like Mosaic, the Internet was on its way to evolving into the samehighly interactive medium that they had envisioned for cable TV. As a prototype, Naughton wrote a small browser, Web Runner (named after the movie Blade Runner), later renamed Hot Java.That year, the language was renamed Java after a trademark search revealed that Oak was used by Oak Technology. Although Java 1.0a was available for download in 1994, the first public release of Java was 1.0a2 with the Hot Java browser on May 23, 1995, announced by Gage at the Sun World conference. His announcement was accompanied by a surprise announcement by Marc Andreessen, Executive Vice President of Netscape Communications Corporation, that Netscape browsers would be including Java support. On January 9, 1996, the Java Soft group was formed by Sun Microsystems to develop the technology.Java编程语言Java是一种通用的,并发的,基于类的并且是面向对象的计算机编程语言,它是为实现尽可能地减少执行的依赖关系而特别设计的。
Java百度翻译API中⽂转英⽂接⼊Java 百度翻译 API 中⽂转英⽂接⼊业务上遇到了语⾔国际化的需求,需要将中⽂的 json 字符串翻译成英⽂,通过百度翻译 API 接⼝来实现翻译功能。
1、平台认证登录百度翻译开放平台,找到通⽤翻译模块,提交申请。
申请通过后,就能直接使⽤了,默认为标准版,完全免费:2、Java demo 配置翻译开放平台⾮常友好,提供了许多常⽤语⾔的 demo 下载,稍微修改下便能使⽤了。
demo 配置好 appid 及密钥,运⾏便能看到控制台中⽂成功翻译成了英⽂:3、封装接⼝我的⽬标是将⼀长串的中⽂ json 翻译成英⽂ json, 上⾯的 demo 是满⾜不了需求的,可以创建⼀个 springboot 项⽬,将 demo 代码迁移到项⽬中,封装⼀个接⼝实现业务需求。
项⽬结构如下:3.1、⾃定义接⼝先引⼊fastJson依赖:<!--fastJson--><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.70</version></dependency>接⼝参数接收⼀长串的中⽂ json ,翻译完成后返回英⽂ json:3.1.1、直接创建线程版本package com.lin.translate.controller;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONArray;import com.lin.translate.config.TransApi;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import java.io.UnsupportedEncodingException;import .URLDecoder;import java.util.List;import java.util.Map;@Controller@RequestMapping("/com/lin")public class TranslateController {// 在平台申请的APP_ID 详见 /api/trans/product/desktop?req=developerprivate static final String APP_ID = "";private static final String SECURITY_KEY = "";@GetMapping("/translate")@ResponseBodypublic Map<String, Map<String, String>> toTranslate(@RequestBody Map<String, Map<String, String>> map) throws InterruptedException {TransApi api = new TransApi(APP_ID, SECURITY_KEY);for(String key : map.keySet()) {Map<String, String> childMap = map.get(key);StringBuilder builder = new StringBuilder();for (String childKey : childMap.keySet()) {//需要翻译的中⽂builder.append(childMap.get(childKey)).append("\n");}//创建线程Thread thread = new Thread() {@Overridepublic void run() {String result = api.getTransResult(builder.toString(), "auto", "en");System.out.println(result);//转成mapMap<String, String> mapResult = JSON.parseObject(result, Map.class);List<Map<String, String>> transResult = (List<Map<String, String>>)JSONArray.parse(JSON.toJSONString(mapResult.get("trans_result"))); int i = 0;for (String childKey : childMap.keySet()) {//获取翻译结果String transQuery = transResult.get(i).get("dst");try {//解码transQuery= URLDecoder.decode(transQuery,"utf-8");} catch (UnsupportedEncodingException e) {e.printStackTrace();}childMap.put(childKey, transQuery);i++;}try {//睡眠⼀秒Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}};thread.start();//主线程阻塞,等待⼦线程结束thread.join();}return map;}}3.1.2、线程池版本package com.lin.translate.controller;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONArray;import com.lin.translate.config.TransApi;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import java.io.UnsupportedEncodingException;import .URLDecoder;import java.util.List;import java.util.Map;import java.util.concurrent.*;@Controller@RequestMapping("/com/lin")public class ExecutorController {// 在平台申请的APP_ID 详见 /api/trans/product/desktop?req=developerprivate static final String APP_ID = "";private static final String SECURITY_KEY = "";@GetMapping("/executorTranslate")@ResponseBodypublic Map<String, Map<String, String>> toTranslate(@RequestBody Map<String, Map<String, String>> map) throws InterruptedException {TransApi api = new TransApi(APP_ID, SECURITY_KEY);//创建线程池,核⼼线程1,最⼤线程数10,存货时间1分钟,任务队列5,默认的线程⼯⼚,拒绝策略为拒绝并抛出异常ExecutorService executorService = new ThreadPoolExecutor(1, 10, 1, TimeUnit.MINUTES,new ArrayBlockingQueue<>(5, true), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());for (String key : map.keySet()) {Map<String, String> childMap = map.get(key);StringBuilder builder = new StringBuilder();for (String childKey : childMap.keySet()) {//需要翻译的中⽂builder.append(childMap.get(childKey)).append("\n");}//执⾏线程executorService.execute(() -> {String result = api.getTransResult(builder.toString(), "auto", "en");System.out.println("result:" + result);//转成mapMap<String, String> mapResult = JSON.parseObject(result, Map.class);List<Map<String, String>> transResult = (List<Map<String, String>>) JSONArray.parse(JSON.toJSONString(mapResult.get("trans_result"))); int i = 0;for (String childKey : childMap.keySet()) {//获取翻译结果String transQuery = transResult.get(i).get("dst");try {//解码transQuery = URLDecoder.decode(transQuery, "utf-8");} catch (UnsupportedEncodingException e) {e.printStackTrace();}childMap.put(childKey, transQuery);i++;}});//线程池等待时间,这⾥即阻塞2秒executorService.awaitTermination(2, TimeUnit.SECONDS);}//任务执⾏完成后关闭线程池executorService.shutdown();return map;}}3.2、demo 配置类代码HttpGet 类代码如下:package com.baidu.translate.demo;import java.io.BufferedReader;import java.io.Closeable;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import .HttpURLConnection;import .MalformedURLException;import .URL;import .URLEncoder;import java.security.KeyManagementException;import java.security.NoSuchAlgorithmException;import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import java.util.Map;import .ssl.HttpsURLConnection;import .ssl.SSLContext;import .ssl.TrustManager;import .ssl.X509TrustManager;class HttpGet {protected static final int SOCKET_TIMEOUT = 10000; // 10Sprotected static final String GET = "GET";public static String get(String host, Map<String, String> params) {try {// 设置SSLContextSSLContext sslcontext = SSLContext.getInstance("TLS");sslcontext.init(null, new TrustManager[] { myX509TrustManager }, null);String sendUrl = getUrlWithQueryString(host, params);// System.out.println("URL:" + sendUrl);URL uri = new URL(sendUrl); // 创建URL对象HttpURLConnection conn = (HttpURLConnection) uri.openConnection();if (conn instanceof HttpsURLConnection) {((HttpsURLConnection) conn).setSSLSocketFactory(sslcontext.getSocketFactory());}conn.setConnectTimeout(SOCKET_TIMEOUT); // 设置相应超时conn.setRequestMethod(GET);int statusCode = conn.getResponseCode();if (statusCode != HttpURLConnection.HTTP_OK) {System.out.println("Http错误码:" + statusCode);}// 读取服务器的数据InputStream is = conn.getInputStream();BufferedReader br = new BufferedReader(new InputStreamReader(is));StringBuilder builder = new StringBuilder();String line = null;while ((line = br.readLine()) != null) {builder.append(line);}String text = builder.toString();close(br); // 关闭数据流close(is); // 关闭数据流conn.disconnect(); // 断开连接return text;} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (KeyManagementException e) {e.printStackTrace();} catch (NoSuchAlgorithmException e) {e.printStackTrace();}return null;}public static String getUrlWithQueryString(String url, Map<String, String> params) { if (params == null) {return url;}StringBuilder builder = new StringBuilder(url);if (url.contains("?")) {builder.append("&");} else {builder.append("?");}int i = 0;for (String key : params.keySet()) {String value = params.get(key);if (value == null) { // 过滤空的keycontinue;}if (i != 0) {builder.append('&');}builder.append(key);builder.append('=');builder.append(encode(value));i++;}return builder.toString();}protected static void close(Closeable closeable) {if (closeable != null) {try {closeable.close();} catch (IOException e) {e.printStackTrace();}}}/*** 对输⼊的字符串进⾏URL编码, 即转换为%20这种形式** @param input 原⽂* @return URL编码. 如果编码失败, 则返回原⽂*/public static String encode(String input) {if (input == null) {return "";}try {return URLEncoder.encode(input, "utf-8");} catch (UnsupportedEncodingException e) {e.printStackTrace();}return input;}private static TrustManager myX509TrustManager = new X509TrustManager() {@Overridepublic X509Certificate[] getAcceptedIssuers() {return null;}@Overridepublic void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { }@Overridepublic void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { }};}MD5 类代码如下:package com.lin.translate.config;import java.io.*;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;/*** MD5编码相关的类** @author wangjingtao**/public class MD5 {// ⾸先初始化⼀个字符数组,⽤来存放每个16进制字符private static final char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd','e', 'f' };/*** 获得⼀个字符串的MD5值** @param input 输⼊的字符串* @return 输⼊字符串的MD5值**/public static String md5(String input) {if (input == null) {return null;}try {// 拿到⼀个MD5转换器(如果想要SHA1参数换成”SHA1”)MessageDigest messageDigest = MessageDigest.getInstance("MD5");// 输⼊的字符串转换成字节数组byte[] inputByteArray = input.getBytes("utf-8");// inputByteArray是输⼊字符串转换得到的字节数组messageDigest.update(inputByteArray);// 转换并返回结果,也是字节数组,包含16个元素byte[] resultByteArray = messageDigest.digest();// 字符数组转换成字符串返回return byteArrayToHex(resultByteArray);} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {e.printStackTrace();return null;}}/*** 获取⽂件的MD5值** @param file* @returnpublic static String md5(File file) {try {if (!file.isFile()) {System.err.println("⽂件" + file.getAbsolutePath() + "不存在或者不是⽂件");return null;}FileInputStream in = new FileInputStream(file);String result = md5(in);in.close();return result;} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return null;}public static String md5(InputStream in) {try {MessageDigest messagedigest = MessageDigest.getInstance("MD5");byte[] buffer = new byte[1024];int read = 0;while ((read = in.read(buffer)) != -1) {messagedigest.update(buffer, 0, read);}in.close();String result = byteArrayToHex(messagedigest.digest());return result;} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return null;}private static String byteArrayToHex(byte[] byteArray) {// new⼀个字符数组,这个就是⽤来组成结果字符串的(解释⼀下:⼀个byte是⼋位⼆进制,也就是2位⼗六进制字符(2的8次⽅等于16的2次⽅)) char[] resultCharArray = new char[byteArray.length * 2];// 遍历字节数组,通过位运算(位运算效率⾼),转换成字符放到字符数组中去int index = 0;for (byte b : byteArray) {resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];resultCharArray[index++] = hexDigits[b & 0xf];}// 字符数组组合成字符串返回return new String(resultCharArray);}}TransApi 类代码如下:package com.lin.translate.config;import java.util.HashMap;import java.util.Map;public class TransApi {private static final String TRANS_API_HOST = "/api/trans/vip/translate";private String appid;private String securityKey;public TransApi(String appid, String securityKey) {this.appid = appid;this.securityKey = securityKey;public String getTransResult(String query, String from, String to) {Map<String, String> params = buildParams(query, from, to);return HttpGet.get(TRANS_API_HOST, params);}private Map<String, String> buildParams(String query, String from, String to) { Map<String, String> params = new HashMap<String, String>();params.put("q", query);params.put("from", from);params.put("to", to);params.put("appid", appid);// 随机数String salt = String.valueOf(System.currentTimeMillis());params.put("salt", salt);// 签名String src = appid + query + salt + securityKey; // 加密前的原⽂params.put("sign", MD5.md5(src));return params;}}3.3、结果⽰例原中⽂ json:{"login": {"login": "登录","loginLoading": "登录中...","account": "账号","password": "密码","lang": "语⾔","setAddress": "设置服务地址","more": "更多"},"mDns": {"local": "局域⽹","localText": "内的XYMERP服务","useAddress": "当前设置的地址","addressUnAvailable": "⽆法连接此服务器","setAddressTips": "未设置服务地址,⽴刻设置"}}翻译后的英⽂ json:{"login": {"login": "Sign in","loginLoading": "Logging in","account": "account number","password": "password","lang": "language","setAddress": "Set service address","more": "more"},"mDns": {"local": "LAN","localText": "Xymerp service in","useAddress": "Currently set address","addressUnAvailable": "Unable to connect to this server","setAddressTips": "Service address not set, set now"}}以上结果满⾜我的需求了,不满⾜你们需求的就稍微修改下吧。
abstract (关键字) 抽象['.bstr.kt]access vt.访问,存取['.kses]'(n.入口,使用权)algorithm n.算法['.lg.riem]Annotation [java]代码注释[.n.u'tei..n]anonymous adj.匿名的[.'n.nim.s]'(反义:directly adv.直接地,立即[di'rektli, dai'rektli])apply v.应用,适用[.'plai]application n.应用,应用程序[,.pli'kei..n]' (application crash 程序崩溃) arbitrary a.任意的['ɑ:bitr.ri]argument n.参数;争论,论据['ɑ:gjum.nt]'(缩写args)assert (关键字) 断言[.'s.:t] ' (java 1.4 之后成为关键字)associate n.关联(同伴,伙伴) [.'s.u.ieit]attribute n.属性(品质,特征) [.'tribju:t]boolean (关键字) 逻辑的, 布尔型call n.v.调用; 呼叫; [k.:l]circumstance n.事件(环境,状况) ['s.:k.mst.ns]crash n.崩溃,破碎[kr..]cohesion内聚,黏聚,结合[k.u'hi:..n](a class is designed with a single, well-focoused purpose. 应该不止这点) command n. 命令,指令[k.'mɑ:nd](指挥, 控制) (command-line 命令行)Comments [java]文本注释['k.ments]compile [java] v.编译[k.m'pail]' Compilation n.编辑[,k.mpi'lei..n] const (保留字)constant n. 常量, 常数, 恒量['k.nst.nt]continue (关键字)coupling耦合,联结['k.pli.]making sure that classes know about other classes only through their APIs. declare [java]声明[di'kl..]default (关键字) 默认值; 缺省值[di'f.:lt]delimiter定义符; 定界符Encapsulation[java]封装(hiding implementation details)Exception [java]例外; 异常[ik'sep..n]entry n.登录项, 输入项, 条目['entri]enum (关键字)execute vt.执行['eksikju:t]exhibit v.显示, 陈列[ig'zibit]exist存在, 发生[ig'zist] '(SQL关键字exists)extends (关键字) 继承、扩展[ik'stend]false (关键字)final (关键字) finally (关键字)fragments段落; 代码块['fr.gm.nt]FrameWork [java]结构,框架['freimw.:k]Generic [java]泛型[d.i'nerik]goto (保留字) 跳转heap n.堆[hi:p]implements (关键字) 实现['implim.nt]import (关键字) 引入(进口,输入)Info n.信息(information [,inf.'mei..n] )Inheritance [java]继承[in'herit.ns] (遗传,遗产)initialize预置初始化[i'iz]instanceof (关键字) 运算符,用于引用变量,以检查这个对象是否是某种类型。
英文原文:Title: Business Applications of Java. Author: Erbschloe, Michael, Business Applications of Java -- Research Starters Business, 2008DataBase: Research Starters - BusinessBusiness Applications of JavaThis article examines the growing use of Java technology in business applications. The history of Java is briefly reviewed along with the impact of open standards on the growth of the World Wide Web. Key components and concepts of the Java programming language are explained including the Java Virtual Machine. Examples of how Java is being used bye-commerce leaders is provided along with an explanation of how Java is used to develop data warehousing, data mining, and industrial automation applications. The concept of metadata modeling and the use of Extendable Markup Language (XML) are also explained.Keywords Application Programming Interfaces (API's); Enterprise JavaBeans (EJB); Extendable Markup Language (XML); HyperText Markup Language (HTML); HyperText Transfer Protocol (HTTP); Java Authentication and Authorization Service (JAAS); Java Cryptography Architecture (JCA); Java Cryptography Extension (JCE); Java Programming Language; Java Virtual Machine (JVM); Java2 Platform, Enterprise Edition (J2EE); Metadata Business Information Systems > Business Applications of JavaOverviewOpen standards have driven the e-business revolution. Networking protocol standards, such as Transmission Control Protocol/Internet Protocol (TCP/IP), HyperText Transfer Protocol (HTTP), and the HyperText Markup Language (HTML) Web standards have enabled universal communication via the Internet and the World Wide Web. As e-business continues to develop, various computing technologies help to drive its evolution.The Java programming language and platform have emerged as major technologies for performing e-business functions. Java programming standards have enabled portability of applications and the reuse of application components across computing platforms. Sun Microsystems' Java Community Process continues to be a strong base for the growth of the Java infrastructure and language standards. This growth of open standards creates new opportunities for designers and developers of applications and services (Smith, 2001).Creation of Java TechnologyJava technology was created as a computer programming tool in a small, secret effort called "the Green Project" at Sun Microsystems in 1991. The Green Team, fully staffed at 13 people and led by James Gosling, locked themselves away in an anonymous office on Sand Hill Road in Menlo Park, cut off from all regular communications with Sun, and worked around the clock for18 months. Their initial conclusion was that at least one significant trend would be the convergence of digitally controlled consumer devices and computers. A device-independent programming language code-named "Oak" was the result.To demonstrate how this new language could power the future of digital devices, the Green Team developed an interactive, handheld home-entertainment device controller targeted at the digital cable television industry. But the idea was too far ahead of its time, and the digital cable television industry wasn't ready for the leap forward that Java technology offered them. As it turns out, the Internet was ready for Java technology, and just in time for its initial public introduction in 1995, the team was able to announce that the Netscape Navigator Internet browser would incorporate Java technology ("Learn about Java," 2007).Applications of JavaJava uses many familiar programming concepts and constructs and allows portability by providing a common interface through an external Java Virtual Machine (JVM). A virtual machine is a self-contained operating environment, created by a software layer that behaves as if it were a separate computer. Benefits of creating virtual machines include better exploitation of powerful computing resources and isolation of applications to prevent cross-corruption and improve security (Matlis, 2006).The JVM allows computing devices with limited processors or memory to handle more advanced applications by calling up software instructions inside the JVM to perform most of the work. This also reduces the size and complexity of Java applications because many of the core functions and processing instructions were built into the JVM. As a result, software developersno longer need to re-create the same application for every operating system. Java also provides security by instructing the application to interact with the virtual machine, which served as a barrier between applications and the core system, effectively protecting systems from malicious code.Among other things, Java is tailor-made for the growing Internet because it makes it easy to develop new, dynamic applications that could make the most of the Internet's power and capabilities. Java is now an open standard, meaning that no single entity controls its development and the tools for writing programs in the language are available to everyone. The power of open standards like Java is the ability to break down barriers and speed up progress.Today, you can find Java technology in networks and devices that range from the Internet and scientific supercomputers to laptops and cell phones, from Wall Street market simulators to home game players and credit cards. There are over 3 million Java developers and now there are several versions of the code. Most large corporations have in-house Java developers. In addition, the majority of key software vendors use Java in their commercial applications (Lazaridis, 2003).ApplicationsJava on the World Wide WebJava has found a place on some of the most popular websites in the world and the uses of Java continues to grow. Java applications not only provide unique user interfaces, they also help to power the backend of websites. Two e-commerce giants that everybody is probably familiar with (eBay and Amazon) have been Java pioneers on the World Wide Web.eBayFounded in 1995, eBay enables e-commerce on a local, national and international basis with an array of Web sites-including the eBay marketplaces, PayPal, Skype, and -that bring together millions of buyers and sellers every day. You can find it on eBay, even if you didn't know it existed. On a typical day, more than 100 million items are listed on eBay in tens of thousands of categories. Recent listings have included a tunnel boring machine from the Chunnel project, a cup of water that once belonged to Elvis, and the Volkswagen that Pope Benedict XVI owned before he moved up to the Popemobile. More than one hundred million items are available at any given time, from the massive to the miniature, the magical to the mundane, on eBay; the world's largest online marketplace.eBay uses Java almost everywhere. To address some security issues, eBay chose Sun Microsystems' Java System Identity Manager as the platform for revamping its identity management system. The task at hand was to provide identity management for more than 12,000 eBay employees and contractors.Now more than a thousand eBay software developers work daily with Java applications. Java's inherent portability allows eBay to move to new hardware to take advantage of new technology, packaging, or pricing, without having to rewrite Java code ("eBay drives explosive growth," 2007).Amazon (a large seller of books, CDs, and other products) has created a Web Service application that enables users to browse their product catalog and place orders. uses a Java application that searches the Amazon catalog for books whose subject matches a user-selected topic. The application displays ten books that match the chosen topic, and shows the author name, book title, list price, Amazon discount price, and the cover icon. The user may optionally view one review per displayed title and make a buying decision (Stearns & Garishakurthi, 2003).Java in Data Warehousing & MiningAlthough many companies currently benefit from data warehousing to support corporate decision making, new business intelligence approaches continue to emerge that can be powered by Java technology. Applications such as data warehousing, data mining, Enterprise Information Portals (EIP's), and Knowledge Management Systems (which can all comprise a businessintelligence application) are able to provide insight into customer retention, purchasing patterns, and even future buying behavior.These applications can not only tell what has happened but why and what may happen given certain business conditions; allowing for "what if" scenarios to be explored. As a result of this information growth, people at all levels inside the enterprise, as well as suppliers, customers, and others in the value chain, are clamoring for subsets of the vast stores of information such as billing, shipping, and inventory information, to help them make business decisions. While collecting and storing vast amounts of data is one thing, utilizing and deploying that data throughout the organization is another.The technical challenges inherent in integrating disparate data formats, platforms, and applications are significant. However, emerging standards such as the Application Programming Interfaces (API's) that comprise the Java platform, as well as Extendable Markup Language (XML) technologies can facilitate the interchange of data and the development of next generation data warehousing and business intelligence applications. While Java technology has been used extensively for client side access and to presentation layer challenges, it is rapidly emerging as a significant tool for developing scaleable server side programs. The Java2 Platform, Enterprise Edition (J2EE) provides the object, transaction, and security support for building such systems.Metadata IssuesOne of the key issues that business intelligence developers must solve is that of incompatible metadata formats. Metadata can be defined as information about data or simply "data about data." In practice, metadata is what most tools, databases, applications, and other information processes use to define, relate, and manipulate data objects within their own environments. It defines the structure and meaning of data objects managed by an application so that the application knows how to process requests or jobs involving those data objects. Developers can use this schema to create views for users. Also, users can browse the schema to better understand the structure and function of the database tables before launching a query.To address the metadata issue, a group of companies (including Unisys, Oracle, IBM, SAS Institute, Hyperion, Inline Software and Sun) have joined to develop the Java Metadata Interface (JMI) API. The JMI API permits the access and manipulation of metadata in Java with standard metadata services. JMI is based on the Meta Object Facility (MOF) specification from the Object Management Group (OMG). The MOF provides a model and a set of interfaces for the creation, storage, access, and interchange of metadata and metamodels (higher-level abstractions of metadata). Metamodel and metadata interchange is done via XML and uses the XML Metadata Interchange (XMI) specification, also from the OMG. JMI leverages Java technology to create an end-to-end data warehousing and business intelligence solutions framework.Enterprise JavaBeansA key tool provided by J2EE is Enterprise JavaBeans (EJB), an architecture for the development of component-based distributed business applications. Applications written using the EJB architecture are scalable, transactional, secure, and multi-user aware. These applications may be written once and then deployed on any server platform that supports J2EE. The EJB architecture makes it easy for developers to write components, since they do not need to understand or deal with complex, system-level details such as thread management, resource pooling, and transaction and security management. This allows for role-based development where component assemblers, platform providers and application assemblers can focus on their area of responsibility further simplifying application development.EJB's in the Travel IndustryA case study from the travel industry helps to illustrate how such applications could function. A travel company amasses a great deal of information about its operations in various applications distributed throughout multiple departments. Flight, hotel, and automobile reservation information is located in a database being accessed by travel agents worldwide. Another application contains information that must be updated with credit and billing historyfrom a financial services company. Data is periodically extracted from the travel reservation system databases to spreadsheets for use in future sales and marketing analysis.Utilizing J2EE, the company could consolidate application development within an EJB container, which can run on a variety of hardware and software platforms allowing existing databases and applications to coexist with newly developed ones. EJBs can be developed to model various data sets important to the travel reservation business including information about customer, hotel, car rental agency, and other attributes.Data Storage & AccessData stored in existing applications can be accessed with specialized connectors. Integration and interoperability of these data sources is further enabled by the metadata repository that contains metamodels of the data contained in the sources, which then can be accessed and interchanged uniformly via the JMI API. These metamodels capture the essential structure and semantics of business components, allowing them to be accessed and queried via the JMI API or to be interchanged via XML. Through all of these processes, the J2EE infrastructure ensures the security and integrity of the data through transaction management and propagation and the underlying security architecture.To consolidate historical information for analysis of sales and marketing trends, a data warehouse is often the best solution. In this example, data can be extracted from the operational systems with a variety of Extract, Transform and Load tools (ETL). The metamodels allow EJBsdesigned for filtering, transformation, and consolidation of data to operate uniformly on datafrom diverse data sources as the bean is able to query the metamodel to identify and extract the pertinent fields. Queries and reports can be run against the data warehouse that contains information from numerous sources in a consistent, enterprise-wide fashion through the use of the JMI API (Mosher & Oh, 2007).Java in Industrial SettingsMany people know Java only as a tool on the World Wide Web that enables sites to perform some of their fancier functions such as interactivity and animation. However, the actual uses for Java are much more widespread. Since Java is an object-oriented language like C++, the time needed for application development is minimal. Java also encourages good software engineering practices with clear separation of interfaces and implementations as well as easy exception handling.In addition, Java's automatic memory management and lack of pointers remove some leading causes of programming errors. Most importantly, application developers do not need to create different versions of the software for different platforms. The advantages available through Java have even found their way into hardware. The emerging new Java devices are streamlined systems that exploit network servers for much of their processing power, storage, content, and administration.Benefits of JavaThe benefits of Java translate across many industries, and some are specific to the control and automation environment. For example, many plant-floor applications use relatively simple equipment; upgrading to PCs would be expensive and undesirable. Java's ability to run on any platform enables the organization to make use of the existing equipment while enhancing the application.IntegrationWith few exceptions, applications running on the factory floor were never intended to exchange information with systems in the executive office, but managers have recently discovered the need for that type of information. Before Java, that often meant bringing together data from systems written on different platforms in different languages at different times. Integration was usually done on a piecemeal basis, resulting in a system that, once it worked, was unique to the two applications it was tying together. Additional integration required developing a brand new system from scratch, raising the cost of integration.Java makes system integration relatively easy. Foxboro Controls Inc., for example, used Java to make its dynamic-performance-monitor software package Internet-ready. This software provides senior executives with strategic information about a plant's operation. The dynamic performance monitor takes data from instruments throughout the plant and performs variousmathematical and statistical calculations on them, resulting in information (usually financial) that a manager can more readily absorb and use.ScalabilityAnother benefit of Java in the industrial environment is its scalability. In a plant, embedded applications such as automated data collection and machine diagnostics provide critical data regarding production-line readiness or operation efficiency. These data form a critical ingredient for applications that examine the health of a production line or run. Users of these devices can take advantage of the benefits of Java without changing or upgrading hardware. For example, operations and maintenance personnel could carry a handheld, wireless, embedded-Java device anywhere in the plant to monitor production status or problems.Even when internal compatibility is not an issue, companies often face difficulties when suppliers with whom they share information have incompatible systems. This becomes more of a problem as supply-chain management takes on a more critical role which requires manufacturers to interact more with offshore suppliers and clients. The greatest efficiency comes when all systems can communicate with each other and share information seamlessly. Since Java is so ubiquitous, it often solves these problems (Paula, 1997).Dynamic Web Page DevelopmentJava has been used by both large and small organizations for a wide variety of applications beyond consumer oriented websites. Sandia, a multiprogram laboratory of the U.S. Department of Energy's National Nuclear Security Administration, has developed a unique Java application. The lab was tasked with developing an enterprise-wide inventory tracking and equipment maintenance system that provides dynamic Web pages. The developers selected Java Studio Enterprise 7 for the project because of its Application Framework technology and Web Graphical User Interface (GUI) components, which allow the system to be indexed by an expandable catalog. The flexibility, scalability, and portability of Java helped to reduce development timeand costs (Garcia, 2004)IssueJava Security for E-Business ApplicationsTo support the expansion of their computing boundaries, businesses have deployed Web application servers (WAS). A WAS differs from a traditional Web server because it provides a more flexible foundation for dynamic transactions and objects, partly through the exploitation of Java technology. Traditional Web servers remain constrained to servicing standard HTTP requests, returning the contents of static HTML pages and images or the output from executed Common Gateway Interface (CGI ) scripts.An administrator can configure a WAS with policies based on security specifications for Java servlets and manage authentication and authorization with Java Authentication andAuthorization Service (JAAS) modules. An authentication and authorization service can bewritten in Java code or interface to an existing authentication or authorization infrastructure. Fora cryptography-based security infrastructure, the security server may exploit the Java Cryptography Architecture (JCA) and Java Cryptography Extension (JCE). To present the user with a usable interaction with the WAS environment, the Web server can readily employ a formof "single sign-on" to avoid redundant authentication requests. A single sign-on preserves user authentication across multiple HTTP requests so that the user is not prompted many times for authentication data (i.e., user ID and password).Based on the security policies, JAAS can be employed to handle the authentication process with the identity of the Java client. After successful authentication, the WAS securitycollaborator consults with the security server. The WAS environment authentication requirements can be fairly complex. In a given deployment environment, all applications or solutions may not originate from the same vendor. In addition, these applications may be running on different operating systems. Although Java is often the language of choice for portability between platforms, it needs to marry its security features with those of the containing environment.Authentication & AuthorizationAuthentication and authorization are key elements in any secure information handling system. Since the inception of Java technology, much of the authentication and authorization issues have been with respect to downloadable code running in Web browsers. In many ways, this had been the correct set of issues to address, since the client's system needs to be protected from mobile code obtained from arbitrary sites on the Internet. As Java technology moved from a client-centric Web technology to a server-side scripting and integration technology, it required additional authentication and authorization technologies.The kind of proof required for authentication may depend on the security requirements of a particular computing resource or specific enterprise security policies. To provide such flexibility, the JAAS authentication framework is based on the concept of configurable authenticators. This architecture allows system administrators to configure, or plug in, the appropriate authenticatorsto meet the security requirements of the deployed application. The JAAS architecture also allows applications to remain independent from underlying authentication mechanisms. So, as new authenticators become available or as current authentication services are updated, system administrators can easily replace authenticators without having to modify or recompile existing applications.At the end of a successful authentication, a request is associated with a user in the WAS user registry. After a successful authentication, the WAS consults security policies to determine if the user has the required permissions to complete the requested action on the servlet. This policy canbe enforced using the WAS configuration (declarative security) or by the servlet itself (programmatic security), or a combination of both.The WAS environment pulls together many different technologies to service the enterprise. Because of the heterogeneous nature of the client and server entities, Java technology is a good choice for both administrators and developers. However, to service the diverse security needs of these entities and their tasks, many Java security technologies must be used, not only at a primary level between client and server entities, but also at a secondary level, from served objects. By using a synergistic mix of the various Java security technologies, administrators and developers can make not only their Web application servers secure, but their WAS environments secure as well (Koved, 2001).ConclusionOpen standards have driven the e-business revolution. As e-business continues to develop, various computing technologies help to drive its evolution. The Java programming language and platform have emerged as major technologies for performing e-business functions. Java programming standards have enabled portability of applications and the reuse of application components. Java uses many familiar concepts and constructs and allows portability by providing a common interface through an external Java Virtual Machine (JVM). Today, you can find Java technology in networks and devices that range from the Internet and scientific supercomputers to laptops and cell phones, from Wall Street market simulators to home game players and credit cards.Java has found a place on some of the most popular websites in the world. Java applications not only provide unique user interfaces, they also help to power the backend of websites. While Java technology has been used extensively for client side access and in the presentation layer, it is also emerging as a significant tool for developing scaleable server side programs.Since Java is an object-oriented language like C++, the time needed for application development is minimal. Java also encourages good software engineering practices with clear separation of interfaces and implementations as well as easy exception handling. Java's automatic memory management and lack of pointers remove some leading causes of programming errors. The advantages available through Java have also found their way into hardware. The emerging new Java devices are streamlined systems that exploit network servers for much of their processing power, storage, content, and administration.中文翻译:标题:Java的商业应用。
外文原文Introduction to Javaautor:Martin Ngobye.source:Computing Static Slice for Java ProgramsJava is designed to meet the challenges of application development in the context of heterogeneous, network-wide distributed environments. Paramount among these challenges is secure delivery of applications that consume the minimum of system resources, can run on any hardware and software platform, and can be extended dynamically.Java originated as part of a research project to develop advanced software for a wide variety of network devices and embedded systems. The goal was to develop a small, reliable, portable, distributed, real-time operating platform. When the project started, C++ was the language of choice. But over time the difficulties encountered with C++ grew to the point where the problems could best be addressed by creating an entirely new language platform. Design and architecture decisions drew from a variety of languages such as Eiffel, SmallTalk, Objective C, and Cedar/Mesa. The result is a language platform that has proven ideal for developing secure, distributed, network based end-user applications in environments ranging from network-embedded devices to the World-Wide Web and the desktop.The design requirements of Java are driven by the nature of the computing environments in which software must be deployed.The massive growth of the Internet and the World-Wide Web leads us to a completely new way of looking at development and distribution of software. To live in the world of electronic commerce and distribution, Java must enable the development of secure, high performance, and highly robust applications on multiple platforms in heterogeneous, distributed networks.Operating on multiple platforms in heterogeneous networks invalidates the traditional schemes of binary distribution, release, upgrade, patch, and so on. To survive in this jungle, Java must be architecture neutral, portable, and dynamically adaptable.The Java system that emerged to meet these needs is simple, so it can be easily programmed by most developers; familiar, so that current developers can easily learn Java; object oriented, to take advantage of modern software development methodologies and to fit into distributed client-server applications; multithreaded, for high performance in applications that need to perform multiple concurrent activities, such as multimedia; and interpreted, for maximum portability and dynamic capabilities.Together, the above requirements comprise quite a collection of buzzwords, so let’sexamine some of them and their respective benefits before going on.What’s completely new is the manner in which Java and its run-time system have combined them to produce a flexible and powerful programming system..Developing your applications using Java results in software that is portable across multiple machine architectures, operating systems, and graphical user interfaces, secure, and high performance, With Java, your job as a software developer is much easier—you focus your full attention on the end goal of shipping innovative products on time, based on the solid foundation of Java. The better way to develop software is here, now, brought to you by the Java language platform.Very dynamic languages like Lisp, TCL, and SmallTalk are often used for prototyping. One of the reasons for their success at this is that they are very robust—you don’t have to worry about freeing or corrupting memory.Similarly, programmers can be relatively fearless about dealing with memory when programming in Java, The garbage collection sy stem makes the programmer’s job vastly easier; with the burden of memory management taken off the programmer’s shoulders, storage allocation errors go away. Another reason commonly given that languages like Lisp, TCL, and SmallTalk are good for prototyping is that they don’t require you to pin down decisions early on—these languages are semantically rich.Java has exactly the opposite property: it forces you to make explicit choices. Along with these choices come a lot of assistance—you can write method invocations and, if you get something wrong, you get told about it at compile time. You don’t have to worry about method invocation error.The Java beginner must grasp 30 basic conceptsBasic concept1.In OOP the only relations is what the object’s interface, such as the computer seller he leaves alone internal structure of electrical source, but he is only concerned about that whether the power will be supplied to you, also so long as know can or not but is not how and why.All procedures are make up of certain attribute and the behavior object, the different object visit invokes through the function invocation, between the object all intercommunion are invoke through the method invocation, By object data encapsulation, enhances reuse rate very much..2.In OOP the most important thought is class, the class is the template ,is a blueprint, construct an object from a class, namely construct an instance of the class.3. Encapsulation: is that combines the data and the behavior in a package) and hides the data the realization process to the object user, in an object data is called its instance field.4.Through expands a class to obtain a new class is called inheritance, but all classes are constructed by the object super root class of expansion, super root class of as follows can make the introduction.5.Object 3 principal characteristicsBehavior--- explained this object can make what.Tate--- when the object exerts the method object reflection.Dentity--- and other similar behavior objects discrimination symbols.Each object has only indentity and among three characteristics they affect mutually.6. Relations among classes:Use-a:Dependent relationHas-a:Polymerization relationIs-a: inheritor relation -- example:A class has inherited B class, this time A class not only has B class of method, but also has its own method(Individuality exists in general character)7.Structure object use structure:Structure proposing, the structure is one special method, the structure object and to its initialization.Example:A Data class of structure calls DataNew Data () --- structure a new object, also initialize current time.Data happyday=new Data () --- an object evaluates an variable happyday, thus enables this object to be used many times, here be stated the cause variable and the object variable are different.New returns the value is a quotation.Constructor characteristic:The constructor may have 0, one or many parametersThe constructor and the class have the same nameA class may have many constructor. The constructor has not returned valueThe constructor always be together used with the new operator8. Over loading: When many methods have the same name when includes the different parameter, then has the over loading Which method does the compiler have to choose invokes.9.Package : Java allow one or many classes to become together as group, is called package, to organizing duty easily, the standard Java storehouse divides into many packages ng java.Util java, net and so on, the package is layered and all java packages are in java and in a javax package.10. Extendable thought: permit to construct new class on existing classes , when you extend the class which already existed, then you reuse this class of method and the field,at the same time you might add the new method and the field in the new class.11.Expandable class:The expandable class fully manifested is-a to extend the relations The form is:Class (subclass) extends (base class).12. Multi-modality: In java, the object variable is multi-modality But in java does not support multiple extend.13.Dynamic combine: the mechanism of invoking object method mechanism.1) compiler examines object statement type and method name.2) the compiler examines that method invokes parameter type.3) static combine: If the method type is priavte static the final ,compiler can accurately know which method should invoke.4) when the procedure runs and uses dynamic combine to invoke a method, the method edition which then hypothesized machine must invoke x the object actual type which aims at to match.5) dynamic combine: is a very important characteristic, it can cause the procedure to change again may expand but does not need to translate has saved the code.14.Final class:In order to prevent other people derive the new class from yours class, this class is cannot expanded.15.The dynamic invocation spend longer time than the static invocation expenditure.16.Abstract class:Stipulated or many abstract methods class of itself must define is abstract.Example: Public abstract string getDescripition17.In Java each class is be extended by object class.18. equal and toString method in object class .Equal uses in testing an object is whether equal with another object.ToString returns to represent this object the string of character, each class can nearly over loading this method, in order to returns to the current condition the correct expression.(The toString method is a very important method)19.General programming:Any class of type all values all may replace with a object class of variable.20.The array tabulates: The ArrayList dynamic array tabulates, is a class of storehouse, defines in java.In uitl package, but automatic control array size.21.in class and class of object ,getclass method returns to the class type an example, when the procedure start contains can increase in the main method class, hypothesized confidential increase all classes which he needs, each increase class all must increase the classwhich it needs.22.The class: class might dynamic operate the java code for the compilation the procedure to provide the formidable function reflection, this function was JavaBeans is specially useful, the use reflected Java to be able to support the VB programmer to be familiar with the use the tool.procedure of analysis class ability is called the reflector, in Java to provide this function the package to call ng.The reflect reflection mechanism is extremely formidable.1) when run analysis class ability.2) when run searches observes a class of object.3) realizes the general array operation code.4) provides the method object.But this mechanism mainly aims at the tool but not the application and the procedure.In the reflection mechanism most important part is that permits class that you inspect structure. With to API includes:ng.Reflect.Field returns to the field.Java.Reflect.Method returns to the method.ng.Reflect.Constructor returns to the parameter.Method pointer: Java does not have the method pointer, makes a method address another method, may invoke it in behind, but the interface is the better solution.23. interface: should showing class could do what but not to assign how to do, a class may realize one or many interfaces.24.The interface is not a class, but is to conforms to a interface request class of set of standard.If realizes a interface to need 2 steps:1) the statement class needs to realize assigns the interface.2) provides in the interface all methods definition.Stated a class realizes a interface to need to use the implements key wordsClass actionB implements Comparable its actionb needs to provide the CompareTo method, the interface is not the class, cannot use a new example interface.25.A class only then a super class, but a class can realize many interfaces. In a Java important interface: Cloneable26.The interface and call-back :to programs a commonly used pattern is call-back,in the pattern, you may refer when this class of pattern settled specific time occurs returns toadjusts on the object the method.Example:ActionListener interface monitor.Similar API includes:Java.Swing.JOptionPaneJava.Swing.TimerJava.Awt.Tookit27.Object clone:The clone method is a object protection method, this meant your code cannot simple invoke it.28.Inner class an inner class definition is the definition in another class.The reason is:1) an inner class object can visit founds its object realization, including private data.2) about other classes in the same package in that, inner class can be hided.3) the anonymous inner class may the very convenient definition accent.In 4) uses the category to be possible the extremely convenient compilation event driver.29.Agent class (proxy):1) appointing all codes that interfaces request2) all methods (toString equals) that object class define30.Data type:Java is kind of emphasizing type language, each variable all must be declared its types at first, in java altogether has 8 basic types . four kinds are the long, two kinds are the float, one is the char, being used in the Unicode code char, Boolean.1. java is simpleJava and C + + are very similar, but much simpler. All the high-level programming language features, is not absolutely necessary have been deleted. For example, Java does not overload operator, the title of the document, pre-processing, computing pointer, the structure of the joint, multi-dimensional array, templates and implicit type conversion. If you know a little C, C + + or Pascal, you will soon master Java. Here is a simple procedure JavaHelloWorld:publicclassHelloInternet (publicstaticvoidmain (Stringargv []) (System. out. println ( "HelloIn-ternet!")))2. Java is object-orientedJava is an object-oriented programming language. In addition to the simple types,such as digital and Boolean operators in addition, Java is an object of most. As with any object-oriented languages, Java code also organized by category. Each category provides a definition of the object behavior. Another type of succession can be a kind of behavior. In the category of the root level, often the target category. Java support for the single type of inherited hierarchy. This means that each category can only inherit one other category. Some of the language to allow multiple inheritance, but it may cause confusion and unnecessarily complicated language. For example, imagine that an object would inherit two completely different category. Java also supports the kind of summary of the interface. This allows programmers to define the interface methods, and do not have to rush immediately to determine the methods to achieve. A type of interface can be a number of purposes in order to truly multi-inheritance of a number of advantages. The implementation of an object can be any number of interfaces. IDL interface and Java interface very similar. Very easy to set up IDLJ compiler. In other words, Java can be used to create a CORBA object system distributed object system. In the view of many computer systems use IDL interface and CORBA objects, such compatibility is important.3. Java is a type of staticIn a Java program, it is essential to the definition used by the target (number of characters, such as an array) type. This will help programmers quickly found because the procedure when the compiler can detect the type of error. However, Java System objects are also dynamic types. A requirement for the type of dynamic is often possible, so programmers can write the procedures for different types of objects to do different things.4. Is a Java-based compilerWhen running Java programs, which were first compiled into byte code. Byte code is very similar to the machine instructions, so Java program is very efficient. However, the byte code does not specifically for a particular machine, so no need to recompile Java program can be in many different computer implementation. Java source code files were compiled into a category, which is equivalent to process byte code performance. In a Java class file, and an example for all of the variables are in the light of, and for the first time in the implementation of the code be resolved. This makes the code more common and more easily subject to revision, but still high.5. Java is architecture neutralJava language is the same for each computer. For example, simple types are the same: 32-bit integer always, always 64-bit long integers. It is strange, such as C and C + + programming language, and so fashionable it is not the case. As a result of these languages so the definition of freedom, each of the compiler and development environment will bedifferent, so that this process nuisance become a transplant. Java programs can easily gain access to transplants, and there is no need to re-compile.6. Java is a soundJava program can not be caused by the collapse of the computer. Java careful testing of the system memory of each visit, make sure it is legitimate and will not cause any problems. However, even if the Java program may also be wrong. If there is some kind of unexpected things, the process will not collapse, and to abandon the exception. Procedures for such an exception would be found to address them. Traditional computer programs can access the full memory. May (unconsciously) to amend any of the value of memory, which will cause problems. Java program can only access memory to allow them access to those parts of the Java program can not modify it does not seek to change the value.7. Java is a compactAs the Java is designed to run on a small computer, as a programming language for the system is relatively small. It effectively in more than 4MB of RAM to run on PC machine. Java translator occupied by only a few hundred KB. This translator for the Java platform independence and portability is reliable. Due to Java is very small, it is a very small computer memory, such as the Java-based PC, as well as television sets, ovens, telephone and home computer, and so on, it is ideal.8. Java is a multi-threadedJava program can run more than one thread. For example, it can be a thread in a time-consuming to complete the calculation, and other users to interact with the threads of dialogue. Therefore, users do not have to stop working, waiting for the Java computing time-consuming process. In the multi-threaded programming environment, it is often difficult because many things may occur at the same time. However, Java provides easy-to-use features simultaneously, so that the programming easier.中文翻译JA V A介绍作者:Martin Ngobye.出处:Computing Static Slice for Java ProgramsJava是被设计用来解决在上下文分布式的异构网络中应用程序开发的问题。
D 科技译文Java Learning Path processEach person's study method is different, a person's method suits another person not necessarily, I only can discuss own study method. Because I study Java am study independently completely, has not asked others, therefore the study process basically is completely oneself tries to find out. I did not know whether this method is the quite good method, only could give everybody to provide refers.Studies Java first step installs good JDK, writes Hello World? Actually the JDK study is not so simple, has two questions about JDK is very easy to puzzle the Java programmer continuously the place: Is the CLASSPATH question, actually said from the principle, is how must make clear JRE ClassLoader increase Class; Another question is package and the import question, how seeks the kind of way question. These two questions tried to find out clear, eliminated has studied Java and uses JDK the biggest barrier. The recommendation looked Wang Sen "the Java Depth Experiences dangers", has carried on the thorough discussion to these two questionsSecond step is studies Java the grammar. The Java grammar is kind of C++, the basically mainstream programming language is not kind of C, is kind of C++, does not have what new thing, therefore the grammar study, probably was the quite a while time is enough. Only needs to pay attention is has the key words usage which several is not easy to make clear, public, protected, private, static, when uses, why has to use, how uses, this possible need some people to direct, I initially was own ponder over completely, has spent the very long time. Butafterwards I saw above this book spoke these concepts to "Thinking in Java".Third step is studies Java the object-oriented programming language characteristic place. For instance inherits, structure, abstract class, the connection, the method are many condition, heavy load, cover, Java exception handling mechanism. Said regarding a not object-oriented language background person that, I thought this process needs to spend the very long very long time, because studies in front of Java does not have C++ the experience, only then the C experience, I was have probably spent for a month, all made clear only then thoroughly these concepts, book example above repeatedly estimating, the revision, the attempt, repeatedly looked at that several chapter of contents, looked, looked has not gotten down 5, comprehended only then thoroughly. But I thought if has the C++ experience, should 12 days time be enough. Then in this process, may have a look "Thinking in Java" this book, opposite is extremely thorough to the object explanation. What a pity is I studies, has not seen to this book, therefore own have spent the massive time, and estimates through own attempt learns.Fourth step starts a familiar Java kind of storehouse. The Java foundation class storehouse actually is JDK installs under the table of contents jre\Lib\Rt.Jar this package. The study foundation class storehouse studies rt.Jar. Inside the foundation class storehouse kind are extremely extremely many. It is said some more than 3,000, I have not counted. But said the most core truly regarding us only then 4, respectively isng.*;Java.Io.*;Java.Util.*;Java.Sql.*;These four packages study, each package study all may write thick teaching material, but O'reilly also truly is does this. I thought if time quite tight, is impossible through to read four books to study. I thought the quite good study method is such:First must read through entire package the frame, understood entire package class, interface, the exception constitution, should better be can find the introduction entire package frame the article. These introduced specially package of books the first several chapters should be these overall frame content introductions. Is not must be familiar with each kind of usage to the package of overall frame assurance, which attributes remembers it have, the method. Wants to record also cannot remember. But is must know which aspects the package does have a kind of constitution, these kind of uses are any, most core several classifications maybe complete any function. I in the time which trains to the human generally is a class speaks a package, therefore not impossible detailed introduction each kind of usage, but I repeatedly stress, how do I speak these packages to you am must tell you a kind of method am transfer, also does not request you to remember the kind of method transfer, but wants you to understand, which kinds Java has provided to us, each kind is uses in any situation, when I meet the question the time, I knew which kind, or which several kind of combinations can solve my problem, That'all! When we write the procedure specifically time, so long as you knew which kind should complete your work with to be enough. Codes, the concrete method transfer, writes the code, Documentation, all things all inside Documentation, will not request you certainly to remember, are actual you also not to be able to remember more than3,000 kinds altogether the nearly 100,000 methods transfers. Therefore changes to each package overall frame assurance extremely importantly.Fifth step, through above study, if study the quite solid speech, built the Java foundation, is left over the work which had to do is sweeps clean inside Documentation besides above 4 packages other some comparisons to have the use the kind. Believed progressed to this step, Java studies independently the ability already to raise, might to study Documentation directly horizontal. Besides must make the GUI programming, inside JDK other can have the use the package is these:Java.Text.*;.*;Javax.Naming.*;These packages of inside real correct uses quite many kinds very are actually few, only then several, therefore does not need to spend the very much time.Sixth step, Java Web programmingThe Web programming core is the HTTP agreement, the HTTP agreement and Java irrelevant, if not familiar HTTP agreement, although also may learn Servlet/JSP programming, but cannot achieve extrapolates, by knowing one method you will know all boundary. Therefore the HTTP agreement study is necessary. If has been familiar with HTTP agreement, also had the Java programming good foundation, studies Servlet/JSP is simply easy as pie, I study Servlet/JSP has used not to week-long time, then started with JSP to make the project. In Servlet/In the JSP study, heavy still was Servlet Documentation. Servlet the API most commonly used kind are very few, the flowered quite fewtime might grasp. These kinds all looked at, writes several examples to try. Servlet/The JSP programming essence is transferring these kinds to come repeatedly through the HTTP agreement converses between Web Server and Brower. Moreover to JSP, but also needs to be familiar with several commonly used JSP the mark, the concrete mode of writing cannot remember the speech, looks up temporarily and that's the end of.In addition Java the Web programming study must place Web Application with emphasis in the design pattern, how carries on the service logic the analysis, and carries on the reasonable design, according to the MVC design pattern request, completes the different logical level separately using Servlet and JSP, how grasps carries on the flow between Servlet and JSP the control and data sharing, as well as how Web should Application dispose and the deployment.Seventh step, J2EE programmingThe above study process if is quite smooth, carries on to this step, the difficulty enhances suddenly. Because the above knowledge content all only involves an aspect, but likes EJB, JMS, core the and so on JTA J2EE standard often is several kind of Java technology synthesis utilization crystallization, therefore grasps the difficulty quite to be big.First certainly must study good JNDI, JNDI is App the Server localization server resources (the EJB module, Datasouce, JMS) searches the method, if to JNDI not familiar, EJB, JMS these things cannot study nearly. JNDI actually is javax.Naming.* This package, utilizes is very simple. The difficulty lies in the server resources document the disposition. Regarding the server resources document disposition, needed to have a look the special documents to be standard, for instance web.Xml mode of writing, ejb-jar.Xml mode of writingand so on. In view of each kind of different App Server, but also has own service resources disposition document, also is needs to be familiar with.Then may study JTA, mainly is must understand JTA regarding business control method, as well as should use JTA in any situation. Here may simple cite an example, we knew the ordinary circumstances may carry on business regarding a database connection (conn.SetAutoCommit (false)....,mit ()), does is an atomic operation, but the supposition my service demand is needs to hold artificially to two different databases is an atomic operation, you can do to? At this time only could use JTA. The supposition operating process inserts a record first toward the A database, then deletes the B database another record, we wrote the code are cannot control entire hold artificially are an atomic operation. With the JTA speech, completes the control by App Server.In studies in front of EJB must study the object sequence and RMI, RMI is the EJB foundation. Then studies JMS and EJB, said regarding EJB, most is essential is must understand how EJB is realizes through RMI to the far-end object transfer, as well as must use in any situation to EJB.In studies EJB, after JMS these things, you possibly can realize must extremely anxiously study two domains the knowledge, is UML, another is Design Pattern. The Java enterprise software design takes the frame extremely (Framework) the design, a good software frame is the software develops the successful essential condition. In this time, should start the study key point to place the design pattern and in the frame study, experiences through the study and the actual programming grasps EJB the design pattern and the J2EE core pattern.Inside J2EE standard, except EJB, JMS, JTA, Servlet/JSP, outside JDBCalso has the very many very many enterprises technology, here 11 did not carry on introducedMoreover also has newest domain Web Services. Web Services also completely does not have any new thing, it likes is one kind of adhesive, may unify the different service provides a unified transfer connection, said as the user, I so long as obtain the service provider for mine WSDL (to service description), has sufficed, I did not know completely the server tenderer provides actually the service is the EJB module,The Net module, any CORBA module, other any realizations, I do not need to know. Web the Services greatest place lies in through the unified service provides the way and the transfer way, has realized the entire Internet service sharing, is an extremely excited area of technology. Web Services resembles at present not to have any very good books, but may through look up the material above the network the way to study.JA V A学习过程每个人的学习方法是不同的,一个人的方法不见得适合另一个人,我只能是谈自己的学习方法。
外文原文Java FundamentalsThe rise of the Internet and the World Wide Web have fundamentally reshaped computing.Only a few short years ago, the cyber landscape was dominated by stand-alone PCs. Today,nearly all PCs are connected to the Internet. The Internet, itself,was transformed—originally offering a convenient way to share files and information, today it is a vast, distributed computing universe. These changes have been as rapid as they have been profound, and in their wake, they gave rise to a new way to program:Java. Java is the preeminent language of the Internet, but it is more than that. Java has revolutionized programming,changing the way that we think about both the form and the function of a program. To be a professional programmer today implies the ability to program in Java—it has become that important. In the course of this book, you will learn the skills needed to master it. The purpose of this module is to introduce you to Java, including its history, its design philosophy, and several of its most important features. By far, the hardest thing about learning a programming language is the fact that no element exists in isolation. Instead, the components of the language work in conjunction with each other. This interrelatedness is especially pronounced in Java. In fact,it is difficult to discuss one aspect of Java without involving others. To help overcome this problem,this module provides a brief overview of several Java features, including the general form of a Java program, some basic control structures, and operators. It does not go into too many details but, rather, concentrates on the general concepts common to any Java program.1.1 The Origins of JavaComputer language innovation is driven forward by two factors: improvements in the art of programming and changes in the computing environment.Java is no exception. Building upon the rich legacy inherited from C and C++,Java adds refinements and features that reflect the current state of the art in programming.Responding to the rise of the online environment,Java offers features that streamline programming for a highly distributed architecture.Java was conceived by James Gosling, Patrick Naughton,Chris Warth,Ed Frank, and Mike Sheridan at Sun Microsystems in 1991. This language was initially called “Oak”but was renamed“Java”in 1995. Somewhat surprisingly, the original impetus for Java was not the Internet! Instead, the primary motivation was the need for a platform-independent language that could be used to create software to be embedded in various consumerelectronic devices, such as toasters, microwave ovens, and remote controls. As you can probably guess, many different types of CPUs are used as controllers. The trouble was that most computer languages are designed to be compiled for a specific target. For example, consider C++.Although it is possible to compile a C++ program for just about any type of CPU, to do so requires a full C++compiler targeted for that CPU. The problem, however,is that compilers are expensive and time-consuming to create. In an attempt to find a better solution, Gosling Java Fundamentals and others worked on a portable, cross-platform language that could produce code that would run on a variety of CPUs under differing environments.This effort ultimately led to the creation of Java.About the time that the details of Java were being worked out, a second, and ultimately more important, factor emerged that would play a crucial role in the future of Java. This second force was, of course, the World Wide Web. Had the Web not taken shape at about the same time that Java was being implemented, Java might have remained a useful but obscure language for programming consumer electronics. However,with the emergence of the Web, Java was propelled to the forefront of computer language design, because the Web, too, demanded portable programs.Most programmers learn early in their careers that portable programs are as elusive as they are desirable. While the quest for a way to create efficient, portable (platform-independent)programs is nearly as old as the discipline of programming itself, it had taken a back seat to other, more pressing problems.However,with the advent of the Internet and the Web, the old problem of portability returned with a vengeance. After all, the Internet consists of a diverse, distributed universe populated with many types of computers, operating systems, and CPUs.What was once an irritating but a low-priority problem had become a high-profile necessity.By 1993 it became obvious to members of the Java design team that the problems of portability frequently encountered when creating code for embedded controllers are also found when attempting to create code for the Internet. This realization caused the focus of Java to switch from consumer electronics to Internet programming.So, while it was the desire for an architecture-neutral programming language that provided the initial spark, it was the Internet that ultimately led to Java’s large-scale success.How Java Relates to C and C++Java is directly related to both C and C++. Java inherits its syntax from C. Its object model is adapted from C++.Java’s relationship with C and C++ is important for several reasons. First, many programmers are familiar with the C/C++ syntax. This makes it easy fora C/C++programmer to learn Java and,conversely,for a Java programmer to learn C/C++.Second, Java’s designers did not “reinvent the wheel.”Instead, they further refined an already highly successful programming paradigm.The modern age of programming began with C. It moved to C++, and now to Java. By inheriting and building upon that rich heritage, Java provides a powerful, logically consistent programming environment that takes the best of the past and adds new features required by the online environment. Perhaps most important, because of their similarities, C, C++, and Java define a common,conceptual framework for the professional programmer.Programmers do not face major rifts when switching from one language to another.One of the central design philosophies of both C and C++ is that the programmer is in charge!Java also inherits this philosophy.Except for those constraints imposed by the Internet environment, Java gives you, the programmer, full control. If you program well, your programs reflect it. If you program poorly, your programs reflect that,too. Put differently, Java is not a language with training wheels.It is a language for professional programmers.Java has one other attribute in common with C and C++: it was designed,tested, and refined by real, working programmers. It is a language grounded in the needs and experiences of the people who devised it. There is no better way to produce a top-flight professional programming language.Because of the similarities between Java and C++, especially their support for objectoriented programming, it is tempting to think of Java as simply the “Internet version of C++.”However, to do so would be a mistake. Java has significant practical and philosophical differences. Although Java was influenced by C++, it is not an enhanced version of C++. For example,it is neither upwardly nor downwardly compatible with C++.Of course, the similarities with C++ are significant, and if you are a C++ programmer, you will feel right at home with Java. Another point: Java was not designed to replace C++. Java was designed to solve a certain set of problems.C++ was designed to solve a different set of problems. Both will coexist for many years to come.How Java Relates to C#Recently a new language called C# has come on the scene. Created by Microsoft to support its .NET Framework, C# is closely reated to Java. In fact, many of C#’s features were directly adapted from Java. Both Java and C# share the same general C++-style syntax, support distributed programming,and utilize the same object model.There are, of course, differences between Java and C#, but the overall “look and feel”of these languages is very similar. This means that if you already know C#, then learning Java will be especially easy. Conversely, if C# is in your future, then your knowledge of Java will come in handy. Giventhe similarity between Java and C#, one might naturally ask, “Will C# replace Java?”The answer is No. Java and C# are optimized for two different types of computing environments. Just as C++ and Java will co-exist for a long time to come, so will C#and Java.1.2 Java’s Contribution to the InternetThe Internet helped catapult Java to the forefront of programming, and Java, in turn, has had a profound effect on the Internet. The reason for this is quite simple: Java expands the universe of objects that can move about freely in cyberspace. In a network, there are two very broad categories of objects that are transmitted between the server and your personal computer:passive information and dynamic,active programs.For example,when you read your e-mail, you are viewing passive data. Even when you download a program, the program’s code is still only passive data until you execute it. However,a second type of object can be transmitted to your computer: a dynamic,self-executing program. Such a program is an active agent on the client computer,yet it is initiated by the server.For example, a program might be provided by the server to properly display the data that it is sending.As desirable as dynamic, networked programs are, they also present serious problems in the areas of security and portability. Prior to Java, cyberspace was effectively closed to half of the entities that now live there. As you will see, Java addresses those concerns and, in doing so, has defined a new form of program: the applet.Java Applets and ApplicationsJava can be used to create two types of programs:applications and applets. An application is a program that runs on your computer,under the operating system of that computer. An application created by Java is more or less like one created using any other type of computer language, such as Visual Basic or C++. When used to create applications, Java is not much different from any other computer language.Rather, it is Java’s ability to create applets that makes it important. An applet is an application designed to be transmitted over the Internet and executed by a Java-compatible Web browser. Although any computer language can be used to create an application, only Java can be used to create an applet. The reason is that Java solves two of the thorniest problems associated with applets: security and portability.Before continuing,let’s define what these two terms mean relative to the Internet.SecurityAs you are almost certainly aware, every time you download a “normal”program,you are risking a viral infection. Prior to Java, most users did not download executable programs frequently, and those that did, scanned them for viruses prior to execution. Even so, most users still worried about the possibility of infecting their systems with a virus or allowing a malicious program to run wild in their systems. (A malicious program might gather privateinformation, such as credit card numbers, bank account balances, and passwords by searching the contents of your computer’s local file system.) Java answers these concerns by providing a firewall between a networked application and your computer.When using a Java-compatible web browser, it is possible to safely download Java applets without fear of viral infection. The way that Java achieves this is by confining a Java program to the Java execution environment and not allowing it access to other parts of the computer. (You will see how this is accomplished, shortly.) Frankly, the ability to download applets with confidence that no harm will be done to the client computer is the single most important aspect of Java.PortabilityAs discussed earlier,many types of computers and operating systems are connected to the Internet. For programs to be dynamically downloaded to all of the various types of platforms, some means of generating portable executable code is needed.As you will soon see, the same mechanism that helps ensure security also helps create portability. Indeed, Java’s solution to these two problems is both elegant and efficient.外文翻译JAVA的基础互联网和万维网的崛起已经从根本上重塑了计算。
Java Technical DescriptionJava as a Programming Platform.Java is certainly a good programming language. There is no doubt that it is one of the better languages available to serious programmers. We think it could potentially have been a great programming language, but it is probably too late for that. Once a language is out in the field, the ugly reality of compatibility with existing code sets in."Java was never just a language. There are lots of programming languages out there, and few of them make much of a splash. Java is a whole platform, with a huge library, containing lots of reusable code, and an execution environment that provides services such as security, portability across operating systems, and automatic garbage collection.As a programmer, you will want a language with a pleasant syntax and comprehensible semantics (i.e., not C++). Java fits the bill, as do dozens of other fine languages. Some languages give you portability, garbage collection, and the like, but they don't have much of a library, forcing you to roll your own if you want fancy graphics or networking or database access. Well, Java has everything—a good language, a high-quality execution environment, and a vast library. That combination is what makes Java an irresistible proposition to so many programmers.Features of Java.1.SimpleWe wanted to build a system that could be programmed easily without a lot of esoteric training and which leveraged today's standard practice. So even though we found that C++ was unsuitable, we designed Java as closely to C++ as possible in order to make the system more comprehensible. Java omits many rarely used, poorly understood, confusing features of C++ that, in our experience, bring more grief than benefit.The syntax for Java is, indeed, a cleaned-up version of the syntax for C++. There is no need for header files, pointer arithmetic (or even a pointer syntax), structures, unions, operator overloading, virtual base classes, and so on. (See the C++ notes interspersed throughout the text for more on the differences between Java and C++.) The designers did not, however, attempt to fix all of the clumsy features of C++. For example, the syntax of the switch statement is unchanged in Java. If you know C++, you will find the transition to the Java syntax easy.If you are used to a visual programming environment (such as Visual Basic), you will not find Java simple. There is much strange syntax (though it does not take long to get the hang of it). More important, you must do a lot more programming in Java. The beauty of Visual Basic is that its visual design environment almost automatically provides a lot of the infrastructure for an application. The equivalent functionality must be programmed manually, usually with a fair bit of code, in Java. There are, however, third-party development environments that provide "drag-and-drop"-style program development.Another aspect of being simple is being small. One of the goals of Java is to enable the construction of software that can run stand-alone in small machines. The size of the basic interpreter and class support is about 40K bytes; adding the basic standard libraries and thread support (essentially a self-contained microkernel) adds an additional 175K.2. Object OrientedSimply stated, object-oriented design is a technique for programming that focuses on the data (= objects) and on the interfaces to that object. To make an analogy with carpentry, an "object-oriented" carpenter would be mostly concerned with the chair he was building, and secondarily with the tools used to make it; a "non-object-oriented" carpenter would think primarily of his tools. The object-oriented facilities of Java are essentially those of C++.Object orientation has proven its worth in the last 30 years, and it is inconceivable that a modern programming language would not use it. Indeed, the object-oriented features of Java are comparable to those of C++. The major differencebetween Java and C++ lies in multiple inheritance, which Java has replaced with the simpler concept of interfaces, and in the Java metaclass model. The reflection mechanism and object serialization feature make it much easier to implement persistent objects and GUI builders that can integrate off-the-shelf components.3. DistributedJava has an extensive library of routines for coping with TCP/IP protocols like HTTP and FTP. Java applications can open and access objects across the Net via URLs with the same ease as when accessing a local file system. We have found the networking capabilities of Java to be both strong and easy to use. Anyone who has tried to do Internet programming using another language will revel in how simple Java makes onerous tasks like opening a socket connection. (We cover networking in Volume 2 of this book.) The remote method invocation mechanism enables communication between distributedobjects (also covered in Volume 2).There is now a separate architecture, the Java 2 Enterprise Edition (J2EE), that supports very large scale distributed applications.4. RobustJava is intended for writing programs that must be reliable in a variety of ways. Java puts a lot of emphasis on early checking for possible problems, later dynamic (run-time) checking, and eliminating situations that are error-prone.… The single biggest difference between Java and C/C++ is that Java has a pointer model that eliminates the possibility of overwriting memory and corrupting data.This feature is also very useful. The Java compiler detects many problems that, in other languages, would show up only at run time. As for the second point, anyone who has spent hours chasing memory corruption caused by a pointer bug will be very happy with this feature of Java.If you are coming from a language like Visual Basic that doesn't explicitly use pointers, you are probably wondering why this is so important. C programmers are not so lucky. They need pointers to access strings, arrays, objects, and even files. In Visual Basic, you do not use pointers for any of these entities, nor do you need to worry about memory allocation for them. On the other hand, many data structures aredifficult to implement in a pointerless language. Java gives you the best of both worlds. You do not need pointers for everyday constructs like strings and arrays. You have the power of pointers if you need it, for example, for linked lists. And you always have complete safety, because you can never access a bad pointer, make memory allocation errors, or have to protect against memory leaking away.5. SecureJava is intended to be used in networked/distributed environments. Toward that end, a lot of emphasis has been placed on security. Java enables the construction of virus-free, tamper-free systems.In the first edition of Core Java we said: "Well, one should 'never say never again,'" and we turned out to be right. Not long after the first version of the Java Development Kit was shipped, a group of security experts at Princeton University found subtle bugs in the security features of Java 1.0. Sun Microsystems has encouraged research into Java security, making publicly available the specification and implementation of the virtual machine and the security libraries. They have fixed all known security bugs quickly. In any case, Java makes it extremely difficult to outwit its security mechanisms. The bugs found so far have been very technical and few in number. From the beginning, Java was designed to make certain kinds of attacks impossible, among them:∙Overrunning the runtime stack—a common attack of worms and viruses Corrupting memory outside its own process space Reading or writing files without permission.∙A number of security features have been added to Java over time. Since version1.1, Java has the notion of digitally signed classesWith a signed class, you can be sure who wrote it. Any time you trust the author of the class, the class can be allowed more privileges on your machine.6. Architecture NeutralThe compiler generates an architecture-neutral object file format—the compiled code is executable on many processors, given the presence of the Java runtime system.The Java compiler does this by generating bytecode instructions which have nothing to do with a particular computerarchitecture. Rather, they are designed to be both easy to interpret on any machine and easily translated into native machine code on the fly.This is not a new idea. More than 20 years ago, both Niklaus Wirth's original implementation of Pascal and the UCSD Pascal system used the same technique. Of course, interpreting bytecodes is necessarily slower than running machine instructions at full speed, so it isn't clear that this is even a good idea. However, virtual machines have the option of translating the most frequently executed bytecode sequences into machine code, a process called just-in-time compilation. This strategy has proven so effective that even Microsoft's .NET platform relies on a virtual machine.The virtual machine has other advantages. It increases security because the virtual machine can check the behavior of instruction sequences. Some programs even produce bytecodes on the fly, dynamically enhancing the capabilities of a running program.7. PortableUnlike C and C++, there are no "implementation-dependent" aspects of the specification. The sizes of the primitive data types are specified, as is the behavior of arithmetic on them.For example, an int in Java is always a 32-bit integer. In C/C++, int can mean a 16-bit integer, a 32-bit integer, or any other size that the compiler vendor likes. The only restriction is that the int type must have at least as many bytes as a short int and cannot have more bytes than a long int. Having a fixed size for number types eliminates a major porting headache. Binary data is stored and transmitted in a fixed format, eliminating confusion about byte ordering. Strings are saved in a standard Unicode format.The libraries that are a part of the system define portable interfaces. For example, there is an abstract Window class and implementations of it for UNIX, Windows, and the Macintosh.As anyone who has ever tried knows, it is an effort of heroic proportions to write a program that looks good on Windows, the Macintosh, and 10 flavors of UNIX. Java1.0 made the heroic effort, delivering a simple toolkit that mapped common user interface elements to a number of platforms.Unfortunately, the result was a library that, with a lot of work, could give barely acceptable results on different systems. (And there were often different bugs on the different platform graphics implementations.) But it was a start. There are many applications in which portability is more important than user interface slickness, and these applications did benefit from early versions of Java. By now, the user interface toolkit has been completely rewritten so that it no longer relies on the host user interface. The result is far more consistent and, we think, more attractive than in earlier versions of Java.8. InterpretedThe Java interpreter can execute Java bytecodes directly on any machine to which the interpreter has been ported. Since linking is a more incremental and lightweight process, the development process can be much more rapid and exploratory.Incremental linking has advantages, but its benefit for the development process is clearly overstated. In any case, we have found Java development tools to be quite slow. If you are used to the speed of the classic Microsoft Visual C++ environment, you will likely be disappointed with the performance of Java development environments. (The current version of Visual Studio isn't as zippy as the classic environments, however. No matter what languageyou program in, you should definitely ask your boss for a faster computer to run the latest development environments. )9. High PerformanceWhile the performance of interpreted bytecodes is usually more than adequate, there are situations where higher performance is required. The bytecodes can be translated on the fly (at run time) into machine code for the particular CPU the application is running on.If you use an interpreter to execute the bytecodes, "high performance" is not the term that we would use. However, on many platforms, there is also another form ofcompilation, the just-in-time (JIT) compilers. These work by compiling the bytecodes into native code once, caching the results, and then calling them again if needed. This approach speeds up commonly used code tremendously because one has to do the interpretation only once. Although still slightly slower than a true native code compiler, a just-in-time compiler can give you a 10- or even 20-fold speedup for some programs and will almost always be significantly faster than an interpreter. This technology is being improved continuously and may eventually yield results that cannot be matched by traditional compilation systems. For example, a just-in-time compiler can monitor which code is executed frequently and optimize just that code for speed.10. MultithreadedThe enefits of multithreading are better interactive responsiveness and real-time behavior.if you have ever tried to do multithreading in another language, you will be pleasantly surprised at how easy it is in Java. Threads in Java also can take advantage of multiprocessor systems if the base operating system does so. On the downside, thread implementations on the major platforms differ widely, and Java makes no effort to be platform independent in this regard. Only the code for calling multithreading remains the same across machines; Java offloads the implementation of multithreading to the underlying operating system or a thread library. Nonetheless, the ease of multithreading is one of the main reasons why Java is such an appealing language for server-side development.11. DynamicIn a number of ways, Java is a more dynamic language than C or C++. It was designed to adapt to an evolving environment. Libraries can freely add new methods and instance variables without any effect on their clients. In Java, finding out run time type information is straightforward.This is an important feature in those situations in which code needs to be added to a running program. A prime example is code that is downloaded from the Internet to run in a browser. In Java 1.0, finding out runtime type information was anything but straightforward, but current versions of Java give the programmer full insight intoboth the structure and behavior of its objects. This is extremely useful for systems that need to analyze objects at run time, such as Java GUI builders, smart debuggers, pluggable components, and object databases.Java技术介绍Java是一种程序设计平台Java是一种优秀的程序设计语言。
外文原文Introduction to Javaautor:Martin Ngobye、source:Computing Static Slice for Java ProgramsJava is designed to meet the challenges of application development in the context of heterogeneous, network-wide distributed environments、Paramount among these challenges is secure delivery of applications that consume the minimum of system resources, can run on any hardware and software platform, and can be extended dynamically、Java originated as part of a research project to develop advanced software for a wide variety of network devices and embedded systems、The goal was to develop a small, reliable, portable, distributed, real-time operating platform、When the project started, C++ was the language of choice、But over time the difficulties encountered with C++ grew to the point where the problems could best be addressed by creating an entirely new language platform、Design and architecture decisions drew from a variety of languages such as Eiffel, SmallTalk, Objective C, and Cedar/Mesa、The result is a language platform that has proven ideal for developing secure, distributed, network based end-user applications in environments ranging from network-embedded devices to the World-Wide Web and the desktop、The design requirements of Java are driven by the nature of the computing environments in which software must be deployed、The massive growth of the Internet and the World-Wide Web leads us to a completely new way of looking at development and distribution of software、To live in the world of electronic commerce and distribution, Java must enable the development of secure, high performance, and highly robust applications on multiple platforms in heterogeneous, distributed networks、Operating on multiple platforms in heterogeneous networks invalidates the traditional schemes of binary distribution, release, upgrade, patch, and so on、To survive in this jungle, Java must be architecture neutral, portable, and dynamically adaptable、The Java system that emerged to meet these needs is simple, so it can be easily programmed by most developers; familiar, so that current developers can easily learn Java; object oriented, to take advantage of modern software development methodologies and to fit into distributed client-server applications; multithreaded, for high performance in applications that need to perform multiple concurrent activities, such as multimedia; and interpreted, for maximum portability and dynamic capabilities、Together, the above requirements comprise quite a collection of buzzwords, so let’s examine some of them and their respective benefits before going on、What’s completely new is the manner in which Java and its run-time system have combined them to produce a flexible and powerful programming system、、Developing your applications using Java results in software that is portable across multiple machine architectures, operating systems, and graphical user interfaces, secure, and high performance, With Java, your job as a software developer is much easier—you focus your full attention on the end goal of shipping innovative products on time, based on the solid foundation of Java、The better way to develop software is here, now, brought to you by the Java language platform、Very dynamic languages like Lisp, TCL, and SmallTalk are often used for prototyping、One of the reasons for their success at this is that they are very robust—you don’t have to worry about freeing or corrupting memory、Similarly, programmers can be relatively fearless about dealing with memory when programming in Java, The garbage collection sys tem makes the programmer’s job vastly easier; with the burden of memory management taken off the programmer’s shoulders, storage allocation errors go away、Another reason commonly given that languages like Lisp, TCL, and SmallTalk are good for prototyping is that they don’t require you to pin down decisions early on—these languages are semantically rich、Java has exactly the opposite property: it forces you to make explicit choices、Along with these choices come a lot of assistance—you can write method invocations and, if you get something wrong, you get told about it at compile time、You don’t have to worry about method invocation error、The Java beginner must grasp 30 basic conceptsBasic concept1、In OOP the only relations is what the object’s interface, such as the computer seller he leaves alone internal structure of electrical source, but he is only concerned about that whether the power will be supplied to you, also so long as know can or not but is not how and why、All procedures are make up of certain attribute and the behavior object, the different object visit invokes through the function invocation, between the object all intercommunion are invoke through the method invocation, By object data encapsulation, enhances reuse rate very much、、2、In OOP the most important thought is class, the class is the template ,is a blueprint, construct an object from a class, namely construct an instance of the class、3、Encapsulation: is that combines the data and the behavior in a package) and hides the data the realization process to the object user, in an object data is called its instance field、4、Through expands a class to obtain a new class is called inheritance, but all classesare constructed by the object super root class of expansion, super root class of as follows can make the introduction、5、Object 3 principal characteristicsBehavior--- explained this object can make what、Tate--- when the object exerts the method object reflection、Dentity--- and other similar behavior objects discrimination symbols、Each object has only indentity and among three characteristics they affect mutually、6、Relations among classes:Use-a:Dependent relationHas-a:Polymerization relationIs-a: inheritor relation -- example:A class has inherited B class, this time A class not only has B class of method, but also has its own method(Individuality exists in general character)7、Structure object use structure:Structure proposing, the structure is one special method, the structure object and to its initialization、Example:A Data class of structure calls DataNew Data () --- structure a new object, also initialize current time、Data happyday=new Data () --- an object evaluates an variable happyday, thus enables this object to be used many times, here be stated the cause variable and the object variable are different、New returns the value is a quotation、Constructor characteristic:The constructor may have 0, one or many parametersThe constructor and the class have the same nameA class may have many constructor、The constructor has not returned valueThe constructor always be together used with the new operator8、Over loading: When many methods have the same name when includes the different parameter, then has the over loading Which method does the compiler have to choose invokes、9、Package : Java allow one or many classes to become together as group, is called package, to organizing duty easily, the standard Java storehouse divides into many packages Java、Lang java、Util java, net and so on, the package is layered and all java packages are in java and in a javax package、10、Extendable thought: permit to construct new class on existing classes , when you extend the class which already existed, then you reuse this class of method and the field, at the same time you might add the new method and the field in the new class、11、Expandable class:The expandable class fully manifested is-a to extend the relations The form is:Class (subclass) extends (base class)、12、Multi-modality: In java, the object variable is multi-modality But in java does not support multiple extend、13、Dynamic combine: the mechanism of invoking object method mechanism、1) compiler examines object statement type and method name、2) the compiler examines that method invokes parameter type、3) static combine: If the method type is priavte static the final ,compiler can accurately know which method should invoke、4) when the procedure runs and uses dynamic combine to invoke a method, the method edition which then hypothesized machine must invoke x the object actual type which aims at to match、5) dynamic combine: is a very important characteristic, it can cause the procedure to change again may expand but does not need to translate has saved the code、14、Final class:In order to prevent other people derive the new class from yours class, this class is cannot expanded、15、The dynamic invocation spend longer time than the static invocation expenditure、16、Abstract class:Stipulated or many abstract methods class of itself must define is abstract、Example: Public abstract string getDescripition17、In Java each class is be extended by object class、18、equal and toString method in object class 、Equal uses in testing an object is whether equal with another object、ToString returns to represent this object the string of character, each class can nearly over loading this method, in order to returns to the current condition the correct expression、(The toString method is a very important method)19、General programming:Any class of type all values all may replace with a object class of variable、20、The array tabulates: The ArrayList dynamic array tabulates, is a class of storehouse, defines in java、In uitl package, but automatic control array size、21、in class and class of object ,getclass method returns to the class type an example, when the procedure start contains can increase in the main method class, hypothesized confidential increase all classes which he needs, each increase class all must increase the class which it needs、22、The class: class might dynamic operate the java code for the compilation the procedure to provide the formidable function reflection, this function was JavaBeans is specially useful, the use reflected Java to be able to support the VB programmer to be familiar with the use the tool、procedure of analysis class ability is called the reflector, in Java to provide this function the package to call Java、Lang、The reflect reflection mechanism is extremely formidable、1) when run analysis class ability、2) when run searches observes a class of object、3) realizes the general array operation code、4) provides the method object、But this mechanism mainly aims at the tool but not the application and the procedure、In the reflection mechanism most important part is that permits class that you inspect structure、With to API includes:Java、Lang、Reflect、Field returns to the field、Java、Reflect、Method returns to the method、Java、Lang、Reflect、Constructor returns to the parameter、Method pointer: Java does not have the method pointer, makes a method address another method, may invoke it in behind, but the interface is the better solution、23、interface: should showing class could do what but not to assign how to do, a class may realize one or many interfaces、24、The interface is not a class, but is to conforms to a interface request class of set of standard、If realizes a interface to need 2 steps:1) the statement class needs to realize assigns the interface、2) provides in the interface all methods definition、Stated a class realizes a interface to need to use the implements key wordsClass actionB implements Comparable its actionb needs to provide the CompareTo method, the interface is not the class, cannot use a new example interface、25、A class only then a super class, but a class can realize many interfaces、In a Java important interface: Cloneable26、The interface and call-back :to programs a commonly used pattern is call-back,in the pattern, you may refer when this class of pattern settled specific time occurs returns to adjusts on the object the method、Example:ActionListener interface monitor、Similar API includes:Java、Swing、JOptionPaneJava、Swing、TimerJava、Awt、Tookit27、Object clone:The clone method is a object protection method, this meant your code cannot simple invoke it、28、Inner class an inner class definition is the definition in another class、The reason is:1) an inner class object can visit founds its object realization, including private data、2) about other classes in the same package in that, inner class can be hided、3) the anonymous inner class may the very convenient definition accent、In 4) uses the category to be possible the extremely convenient compilation event driver、29、Agent class (proxy):1) appointing all codes that interfaces request2) all methods (toString equals) that object class define30、Data type:Java is kind of emphasizing type language, each variable all must be declared its types at first, in java altogether has 8 basic types 、four kinds are the long, two kinds are the float, one is the char, being used in the Unicode code char, Boolean、1、java is simpleJava and C + + are very similar, but much simpler、All the high-level programming language features, is not absolutely necessary have been deleted、For example, Java does not overload operator, the title of the document, pre-processing, computing pointer, the structure of the joint, multi-dimensional array, templates and implicit type conversion、If you know a little C, C + + or Pascal, you will soon master Java、Here is a simple procedure JavaHelloWorld:publicclassHelloInternet (publicstaticvoidmain (Stringargv []) (System、out、println ( "HelloIn-ternet!")))2、Java is object-orientedJava is an object-oriented programming language、In addition to the simple types,such as digital and Boolean operators in addition, Java is an object of most、As with any object-oriented languages, Java code also organized by category、Each category provides a definition of the object behavior、Another type of succession can be a kind of behavior、In the category of the root level, often the target category、Java support for the single type of inherited hierarchy、This means that each category can only inherit one other category、Some of the language to allow multiple inheritance, but it may cause confusion and unnecessarily complicated language、For example, imagine that an object would inherit two completely different category、Java also supports the kind of summary of the interface、This allows programmers to define the interface methods, and do not have to rush immediately to determine the methods to achieve、 A type of interface can be a number of purposes in order to truly multi-inheritance of a number of advantages、The implementation of an object can be any number of interfaces、IDL interface and Java interface very similar、Very easy to set up IDLJ compiler、In other words, Java can be used to create a CORBA object system distributed object system、In the view of many computer systems use IDL interface and CORBA objects, such compatibility is important、3、Java is a type of staticIn a Java program, it is essential to the definition used by the target (number of characters, such as an array) type、This will help programmers quickly found because the procedure when the compiler can detect the type of error、However, Java System objects are also dynamic types、 A requirement for the type of dynamic is often possible, so programmers can write the procedures for different types of objects to do different things、4、Is a Java-based compilerWhen running Java programs, which were first compiled into byte code、Byte code is very similar to the machine instructions, so Java program is very efficient、However, the byte code does not specifically for a particular machine, so no need to recompile Java program can be in many different computer implementation、Java source code files were compiled into a category, which is equivalent to process byte code performance、In a Java class file, and an example for all of the variables are in the light of, and for the first time in the implementation of the code be resolved、This makes the code more common and more easily subject to revision, but still high、5、Java is architecture neutralJava language is the same for each computer、For example, simple types are the same: 32-bit integer always, always 64-bit long integers、It is strange, such as C and C + + programming language, and so fashionable it is not the case、As a result of these languages so the definition of freedom, each of the compiler and development environment will bedifferent, so that this process nuisance become a transplant、Java programs can easily gain access to transplants, and there is no need to re-compile、6、Java is a soundJava program can not be caused by the collapse of the computer、Java careful testing of the system memory of each visit, make sure it is legitimate and will not cause any problems、However, even if the Java program may also be wrong、If there is some kind of unexpected things, the process will not collapse, and to abandon the exception、Procedures for such an exception would be found to address them、Traditional computer programs can access the full memory、May (unconsciously) to amend any of the value of memory, which will cause problems、Java program can only access memory to allow them access to those parts of the Java program can not modify it does not seek to change the value、7、Java is a compactAs the Java is designed to run on a small computer, as a programming language for the system is relatively small、It effectively in more than 4MB of RAM to run on PC machine、Java translator occupied by only a few hundred KB、This translator for the Java platform independence and portability is reliable、Due to Java is very small, it is a very small computer memory, such as the Java-based PC, as well as television sets, ovens, telephone and home computer, and so on, it is ideal、8、Java is a multi-threadedJava program can run more than one thread、For example, it can be a thread in a time-consuming to complete the calculation, and other users to interact with the threads of dialogue、Therefore, users do not have to stop working, waiting for the Java computing time-consuming process、In the multi-threaded programming environment, it is often difficult because many things may occur at the same time、However, Java provides easy-to-use features simultaneously, so that the programming easier、中文翻译JA V A介绍作者:Martin Ngobye、出处:Computing Static Slice for Java ProgramsJava就是被设计用来解决在上下文分布式的异构网络中应用程序开发的问题。
API (Application Programming Interface) 应用编程接口JRE (Java Runtime Enviroment) Java 运行时环境JDK (Java Development Kit) Java开发工具包SDK(Software Development Kit, 即软件开发工具包)JVM (Java Virtual Machine) Java虚拟机JNI (Java Native Interface) Java本地接口AWT (Abstract Windows Toolekit) 抽象窗口工具箱JNDI (Java Naming & Directory Interface) JAVA命名目录服务.主要提供的功能是:提供一个目录系统,让其它各地的应用程序在其上面留下自己的索引,从而满足快速查找和定位分布式应用程序的功能。
JMS (Java Message Service)JAVA消息服务.主要实现各个应用程序之间的通讯.包括点对点和广播.JTA (Java Transcation API) JAVA事务服务.提供各种分布式事务服务.应用程序只需调用其提供的接口即可.JAF (Java Action FrameWork) JAVA安全认证框架.提供一些安全控制方面的框架.让开发者通过各种部署和自定义实现自己的个性安全控制策略.RMI (Remote Method Interface) 远程方法调用CVS (Concurrent Versions System) 版本控制器SVN (Subversion) 版本控制器TC (Test Case) 测试用例,是为某个特殊目标而编制的一组测试输入、执行条件以及预期结果,以便测试某个程序路径或核实是否满足某个特定需求。
指对一项特定的软件产品进行测试任务的描述,体现测试方案、方法、技术和策略。
内容包括测试目标、测试环境、输入数据、测试步骤、预期结果、测试脚本等,并形成文档。
外文资料译文及原文JavaJava I/O 系统对编程语言的设计者来说,创建一套好的输入输出(I/O)系统,是一项难度极高的任务。
这一点可以从解决方案的数量之多上看出端倪。
这个问题难就难在它要面对的可能性太多了。
不仅是因为有那么多 I/O 的源和目地(文件,控制台,网络连接等等),而且还有很多方法(顺序的『sequential』,随机的『random-access』, 缓存的『 buffered 』,二进制的『 binary 』,字符方式的『 character 』,行的『by lines 』,字的『 by words 』,等等)。
Java类库的设计者们用"创建很多类"的办法来解决这个问题。
坦率地说Java I/O 系统的类实在是太多了,以至于初看起来会把人吓着(但是,具有讽刺意味的是,这种设计实际上是限制了类的爆炸性增长)。
此外,Java在1.0版之后又对其 I/O 类库作了重大的修改,原先是面向 byte 的,现在又补充了面向Unicode字符的类库。
为了提高性能,完善功能,JDK1.4又加了一个nio(意思是"new I/O"。
这个名字会用上很多年)。
这么以来,如果你想对Java的I/O 类库有个全面了解,并且做到运用自如,你就得先学习大量的类。
此外,了解 I/O 类库的演化的历史也是相当重要的。
可能你的第一反应是 "别拿什么历史来烦我了,告诉我怎么用就可以了! "但问题是,如果你对这段历史一无所知,很快就会被一些有用或是没用的类给搞糊涂了。
本章会介绍 Java 标准类库中的各种 I/O 类,及其使用方法。
File 类在介绍直接从流里读写数据的类之前,我们先介绍一下处理文件和目录的类。
File 类有一个极具欺骗性的名字;或许你会认为这是一个关于文件的类,但它不是。
你可以用它来表示某个文件的名字,也可以用它来表示目录里一组文件的名字。
如果它表示的是一组文件,那么你还可以用 list( ) 方法来进行查询,让它会返回 String 数组。
由于元素数量是固定的,因此数组会比容器更好一些。
如果你想要获取另一个目录的清单,再建一个 File 对象就是了。
实际上,叫它 "FilePath" 可能会更好一些。
下面我们举例说明怎样使用这个类及其相关的 FilenameFilter 接口。
目录列表器假设你想看看这个目录。
有两个办法。
一是不带参数调用 list( ) 。
它返回的是 File 对象所含内容的完整清单。
但是,如果你要的是一个 " 限制性列表(restricted list)" 的话——比方说,你想看看所有扩展名为 .java 的文件——那么你就得使用 "目录过滤器 " 了。
这是一个专门负责挑选显示 File 对象的内容的类。
下面就是源代码。
看看,用了 java.utils.Arrays.sort( ) 和 11 章的AlphabeticComparator 之后,我们没费吹灰之力就对结果作了排序 ( 按字母顺序)://: c12:DirList.java// Displays directory listing using regular expressions.// {Args: "D.*\.java"} import java.io.*; import java.util.*; importjava.util.regex.*; import com.bruceeckel.util.*; public class DirList { public static void main(String[] args) {File path = new File(".");String[] list;if(args.length == 0)list = path.list();elselist = path.list(new DirFilter(args[0]));Arrays.sort(list, new AlphabeticComparator());for(int i = 0; i < list.length; i++)System.out.println(list[i]);}}class DirFilter implements FilenameFilter {private Pattern pattern;public DirFilter(String regex) {pattern = pile(regex);}public boolean accept(File dir, String name) {// Strip path information, search for regex:return pattern.matcher(new File(name).getName()).matches();} } ///:~DirFilter 实现了 FilenameFilter 接口。
我们来看看 FilenameFilter 究竟有多简单:public interface FilenameFilter {boolean accept(File dir, String name);}也就是说,这类对象的任务就是提供一个 accept( ) 的方法。
之所以要创建这个类,就是要给 list( ) 提供一个 accept( ) 方法,这样当 list( ) 判断该返回哪些文件名的时候,能够 "回过头来调用 "accept( ) 方法。
因此,这种结构通常被称为回调 (callback) 。
更准确地说,由于 list( ) 实现了基本功能,而FilenameFilter 提供了"对外服务所需的算法 " ,因此这是一种 "策略模式 ( Strategy Pattern )" 。
由于 list( ) 拿 FilenameFilter 对象当参数,因此你可以将任何实现FilenameFilter 接口的对象传给它,并以此 ( 甚至是在运行时 ) 控制 list( ) 的工作方式。
回调能提高程序的灵活性。
DirFilter 还告诉我们, interface 只是包含了一些方法,它没说你只能写这些方法。
( 但是,你至少要定义接口里有的方法。
) 这里我们还定义了 DirFilter 的构造函数。
accept( ) 方法需要两个参数,一个是 File 对象,表示这个文件是在哪个目录里面的;另一个是 String ,表示文件名。
虽然你可以忽略它们中的一个,甚至两个都不管,但是你大概总得用一下文件名吧。
记住, list( ) 会对目录里的每个文件调用 accept( ) ,并以此判断是不是把它包括到返回值里;这个判断依据就是accept( ) 的返回值。
切记,文件名里不能有路径信息。
为此你只要用一个 String 对象来创建 File 对象,然后再调用这个 File 对象的 getName( ) 就可以了。
它会帮你剥离路径信息(以一种平台无关的方式)。
然后再在 accept( ) 里面用正则表达式 (regular expression) 的 matcher 对象判断, regex 是否与文件名相匹配。
兜完这个圈子,list( ) 方法返回了一个数组。
匿名内部类这是用匿名内部类 (详见第八章 )来重写程序的绝佳机会。
下面我们先创建一个返回 FilenameFilter 的 filter( ) 方法。
//: c12:DirList2.java// Uses anonymous inner classes.// {Args: "D.*\.java"}import java.io.*;import java.util.*;import java.util.regex.*;import com.bruceeckel.util.*;public class DirList2 {public static FilenameFilter filter(final String regex) {// Creation of anonymous inner class:return new FilenameFilter() {private Pattern pattern = pile(regex);public boolean accept(File dir, String name) {return pattern.matcher(new File(name).getName()).matches();}}; // End of anonymous inner class}public static void main(String[] args) {File path = new File(".");String[] list;if(args.length == 0)list = path.list();elselist = path.list(filter(args[0]));Arrays.sort(list, new AlphabeticComparator());for(int i = 0; i < list.length; i++)System.out.println(list[i]);}} ///:~注意, filter( ) 的参数必须是 final 的。
要想在匿名内部类里使用其作用域之外的对象,只能这么做。
这是对前面所讲的代码的改进,现在 FilenameFilter 类已经与 DirList2 紧紧地绑在一起了。
不过你还可以更进一步,把这个匿名内部类定义成 list( ) 的参数,这样代码会变得更紧凑://: c12:DirList3.java// Building the anonymous inner class "in-place."// {Args: "D.*\.java"}import java.io.*;import java.util.*;import java.util.regex.*;import com.bruceeckel.util.*;public class DirList3 {public static void main(final String[] args) {File path = new File(".");String[] list;if(args.length == 0)list = path.list();elselist = path.list(new FilenameFilter() {private Pattern pattern = pile(args[0]);public boolean accept(File dir, String name) {return pattern.matcher(new File(name).getName()).matches();}});Arrays.sort(list, new AlphabeticComparator());for(int i = 0; i < list.length; i++)System.out.println(list[i]);}} ///:~现在该轮到 main( ) 的参数成 final 了,因为匿名内部类要用它的 arg[0] 了。