20个非常有用的Java程序片段
- 格式:docx
- 大小:31.17 KB
- 文档页数:16
大学java考试题及答案详解大学Java考试题及答案详解一、选择题1. Java是一种______。
A. 编译型语言B. 解释型语言C. 汇编语言D. 机器语言答案:B2. 下列哪个是Java的关键字?A. ObjectB. StringC. voidD. Array答案:C3. Java中的“==”用于比较什么?A. 引用是否相同B. 引用所指向的对象的值是否相同C. 基本数据类型的值是否相等D. 引用所指向的对象的内存地址是否相同答案:C二、填空题1. Java语言支持的四种访问控制级别是:______、______、______和______。
答案:public, protected, default, private2. Java中,______关键字用于定义一个类可以被继承。
答案:extends三、简答题1. 简述Java的垃圾回收机制。
答案:Java的垃圾回收机制是一种自动内存管理功能,它通过垃圾回收器定期检查不再使用的对象,并释放它们占用的内存。
垃圾回收器不会立即回收对象,而是等到确定对象不再被任何引用指向时才进行回收。
四、编程题1. 编写一个Java程序,实现计算两个整数的和。
```javapublic class SumCalculator {public static void main(String[] args) {int num1 = 10;int num2 = 20;int sum = num1 + num2;System.out.println("The sum is: " + sum);}}```答案:程序定义了一个名为SumCalculator的类,其中包含一个main 方法。
在main方法中,定义了两个整数num1和num2,并计算它们的和,最后通过System.out.println输出结果。
五、论述题1. 论述Java的多线程机制及其应用场景。
java 常用代码Java是一种广泛应用于软件开发的编程语言,具有简单易学、跨平台、面向对象等特点。
在Java的开发过程中,有一些常用的代码片段,可以帮助程序员提高开发效率和代码质量。
本文将介绍一些常见的Java常用代码片段。
一、变量声明和赋值在Java中,变量的声明和赋值是非常常见的操作。
声明变量可以使用如下代码片段:```java数据类型变量名;```其中,数据类型可以是Java的基本数据类型,如int、double、boolean等,也可以是引用类型,如String、List等。
变量名则是开发者自定义的变量名称。
变量的赋值可以使用如下代码片段:```java变量名 = 值;```其中,值可以是直接量,也可以是其他变量的值。
二、条件语句在Java的开发中,经常需要根据条件来执行不同的代码逻辑。
条件语句可以使用如下代码片段:```javaif (条件) {// 条件成立时执行的代码} else {// 条件不成立时执行的代码}```其中,条件可以是一个布尔表达式,表示判断的条件。
if语句的后面可以跟上else语句,用于处理条件不成立时的逻辑。
三、循环语句循环语句在Java的开发过程中也是非常常用的。
循环语句可以使用如下代码片段:```javafor (初始化; 条件; 更新) {// 循环体}```其中,初始化是循环开始时执行的语句;条件是循环执行的条件;更新是每次循环结束后执行的语句。
循环体则是需要重复执行的代码。
四、方法定义和调用在Java中,方法是一组可以重复使用的代码块。
方法的定义和调用可以使用如下代码片段:```java修饰符返回类型方法名(参数列表) {// 方法体return 返回值;}```其中,修饰符可以是public、private等,用于控制方法的访问权限;返回类型是方法执行后的返回值类型;方法名是开发者自定义的方法名称;参数列表是方法的输入参数;方法体是方法的具体实现;return语句用于返回方法的返回值。
一、单选题(共60题,每小题1分,共60分)1、Java JDK中调试器的命令是( )。
A.javacB.javaC.jdbD.javah2、运行jar文件中class文件需要在java命令后面加的参数为()。
A.-cp B -g C -d D -verbose3、下面哪项在java中是不合法的标识符?()A.$userB.pointC.You&meD._endline4、下列哪一项不是Java保留字?()A.sizeofB.superC.abstractD.break5、下列哪个布局管理器中的按钮位置有可能会根据Frame的大小改变而改变?()A.BorderLayoutB.CardLayoutC.GridLayoutD.FlowLayout6、下面哪些java语句会导致无限循环?( )I、while (true) i = 0;II、while (false) i = 1;III、while (!false) i = 0;A、III onlyB、I and III onlyC、I onlyD、I, II and III7、下面是Example.java文件的完整代码,请找出会产生编译错误的行()。
1) class BaseClass {2) public String str;3) public BaseClass(){4) System.out.println(“ok”);}5) public BaseClass(String s){6) str=s;}}7) class SubClass extends BaseClass{8) }9) public class Example{10) public void method(){11) SubClass s=new SubClass(“hello”);12) BaseClass b=new BaseClass(“world”);13) }14) }A.7B.10C.11D.128、可以在下面代码段point x处写入的是()。
IntelliJ IDEA 的20 个代码自动完成的特性在这篇文章中,我想向您展示IntelliJ IDEA 中最棒的20 个代码自动完成的特性,可让Java 编码变得更加高效。
对任何集成开发环境来说,代码的自动完成都是最最重要的一项功能,它根据你输入的内容进行预判并帮你自动完成你想输入的代码,有时候甚至都不知道自己想要输入什么,例如一些类名、成员、方法或者是其他方面的内容。
IntelliJ IDEA 中的代码自动完成的功能之所以能让我如此印象深刻,原因是IDEA 真的理解你的代码以及你当前所在的上下文。
接下来我们将这些最重要的特性进行简单的说明,这些特性让IDEA 显示出比其他IDE 更棒的表现。
即刻完成Instant completion第一个也是最吸引我的就是“即刻完成”特性,不同于其他IDE,IDEA 可在任意地方提供这个功能,而不只是当你要访问某个类的成员时。
只需要输入单词的首字母,IntelliJ IDEA 就会立即给出最相关的、最适合此处代码编辑需要的选项共你选择。
想要了解“即刻完成”是多么的有效,你可以浏览这个 .类型感知的自动完成Type-aware completion另一个特性同样打破了常规的代码自动完成的方法,称为:智能自动完成。
你可能已经知道,IDEA 中包含不止一种自动完成的功能,包括基本自动完成⌘Space和智能自动完成⌘⇧Space.当你呼出智能自动完成时,它会将建议列表中的不适用的条目过滤掉,只显示可用的类、变量、属性或者方法,这个提升了性能而且可以避免不必要的错误,如果你试用下这个功能,你肯定会时刻想到它。
静态属性和方法Static fields and methods就如同刚才我说的,IDEA 一直走在你的想法之前。
如果你不记得一些静态成员的类名,你只需要开始输入静态成员的名称,然后调用两次“自动完成”,IDEA 会给你提供正确的可供选择的列表,甚至是通过静态import 进来的方法,如果你调用Intention action ⌥⏎的话.再一次说明,如果你使用智能自动完成, 它将只提供可正确使用的选项。
java 断言的用法全文共四篇示例,供读者参考第一篇示例:Java中的断言是一种用于验证程序假设的有效工具。
断言通常用于帮助开发人员在代码中明确表达预期行为,并在程序运行时检测错误。
在Java中,断言是通过assert关键字来实现的,可以根据条件来判断程序的正确性。
在本文中,我们将深入探讨Java断言的用法及其重要性。
### 1.断言的基本语法在Java中,断言由assert关键字和条件表达式组成。
其基本语法如下:```assert condition;```condition是一个布尔表达式,如果该表达式为true,那么程序将继续执行下去;如果表达式为false,那么将抛出AssertionError异常并终止程序执行。
### 2.如何启用和禁用断言在Java中,断言默认是禁用的,我们可以通过在运行时使用"-ea"参数来启用断言。
例如:```java -ea YourClass```如果想在运行时禁用断言,可以使用"-ea"参数。
例如:```java -da YourClass```### 3.在开发阶段使用断言的重要性在开发过程中,使用断言可以帮助开发人员验证在程序中的前提假设是否正确。
通过断言,开发人员可以在程序中插入一些检查点,帮助发现潜在的错误和问题,从而提高程序的可靠性和稳定性。
### 4.如何正确地使用断言在代码中使用断言时,需要遵循以下一些最佳实践:- 断言通常用于验证程序的内部逻辑,不应该用于检测外部输入的有效性。
- 不要在断言中包含任何会改变程序状态的操作,因为启用和禁用断言可能会改变程序的行为。
- 尽量避免在断言中使用复杂的表达式,因为这可能会使代码难以阅读和维护。
- 在使用断言时,应该避免与异常处理混淆,断言主要用于调试和测试,而异常处理用于处理运行时错误。
### 5.断言的实际应用场景断言在实际的软件开发中有很多应用场景,其中一些常见的包括:- 检查方法的输入参数是否满足条件。
格式化⽇期、时间使⽤ DateFormat 格式化⽇期、时间DateFormat 也是⼀个抽象类,它也提供了如下⼏个类⽅法⽤于获取 DateFormat 对象。
getDateInstance():返回⼀个⽇期格式器,它格式化后的字符串只有⽇期,没有时间。
该⽅法可以传⼊多个参数,⽤于指定⽇期样式和 Locale 等参数;如果不指定这些参数,则使⽤默认参数。
getTimeInstance():返回⼀个时间格式器,它格式化后的字符串只有时间,没有⽇期。
该⽅法可以传⼊多个参数,⽤于指定时间样式和 Locale 等参数;如果不指定这些参数,则使⽤默认参数。
getDateTimeInstance():返回⼀个⽇期、时间格式器,它格式化后的字符串既有⽇期,也有时间。
该⽅法可以传⼊多个参数,⽤于指定⽇期样式、时间样式和 Locale 等参数;如果不指定这些参数,则使⽤默认参数。
上⾯三个⽅法可以指定⽇期样式、时间样式参数,它们是的4个静态常量:FULL、LONG、MEDIUM 和 SHORT,通过这4个样式参数可以控制⽣成的格式化字符串。
看如下例⼦程序。
import java.util.*;import java.text.*;import static java.text.DateFormat.*;public class DateFormatTest {public static void main(String[] args) throws ParseException {// 需要被格式化的时间Date dt = new Date();// 创建两个Locale,分别代表中国、美国Locale[] locales = { Locale.CHINA, };DateFormat[] df = new DateFormat[16];// 为上⾯两个Locale创建16个DateFormat对象for (int i = 0; i < locales.length; i++) {df[i * 8] = DateFormat.getDateInstance(SHORT, locales[i]);df[i * 8 + 1] = DateFormat.getDateInstance(MEDIUM, locales[i]);df[i * 8 + 2] = DateFormat.getDateInstance(LONG, locales[i]);df[i * 8 + 3] = DateFormat.getDateInstance(FULL, locales[i]);df[i * 8 + 4] = DateFormat.getTimeInstance(SHORT, locales[i]);df[i * 8 + 5] = DateFormat.getTimeInstance(MEDIUM, locales[i]);df[i * 8 + 6] = DateFormat.getTimeInstance(LONG, locales[i]);df[i * 8 + 7] = DateFormat.getTimeInstance(FULL, locales[i]);}for (int i = 0; i < locales.length; i++) {String tip = i == 0 ? "----中国⽇期格式----" : "----美国⽇期格式----";System.out.println(tip);System.out.println("SHORT格式的⽇期格式:" + df[i * 8].format(dt));System.out.println("MEDIUM格式的⽇期格式:" + df[i * 8 + 1].format(dt));System.out.println("LONG格式的⽇期格式:" + df[i * 8 + 2].format(dt));System.out.println("FULL格式的⽇期格式:" + df[i * 8 + 3].format(dt));System.out.println("SHORT格式的时间格式:" + df[i * 8 + 4].format(dt));System.out.println("MEDIUM格式的时间格式:" + df[i * 8 + 5].format(dt));System.out.println("LONG格式的时间格式:" + df[i * 8 + 6].format(dt));System.out.println("FULL格式的时间格式:" + df[i * 8 + 7].format(dt));}}}上⾯程序共创建了16个 DateFormat 对象,分别为中国、美国两个 Locale 各创建8个 DateFormat 对象,分别是 SHORT、MEDIUM、LONG、FULL 四种样式的⽇期格式器、时间格式器。
protobuf map 用法概述说明以及解释1. 引言1.1 概述在当前大数据时代,数据结构的高效管理和传输成为了极为重要的问题。
Google 开源的Protocol Buffers(简称protobuf)作为一种轻量级和高效的数据序列化格式,被广泛应用于各类系统间的数据通信和存储操作中。
其中,protobuf map作为protobuf中的一种特殊数据类型,在处理键值对映射关系时具有独特而强大的优势。
本文旨在全面介绍protobuf map的用法,从基本介绍到详细使用方法,并以实际项目中常见场景进行应用示例。
通过阅读本文,读者将能够深入理解protobuf map及其适用性,并掌握相关技术实践经验。
1.2 文章结构本文正文内容分为五个主要部分。
首先是引言部分,概括介绍了文章涉及的话题背景和目标。
接下来,在第二部分中,我们将回顾protobuf基础知识,并对protobuf map进行定义和特点的详细说明,以便读者更好地理解其原理和机制。
第三部分将重点讲解protobuf map在实际使用中的各种操作方法,包括声明、定义、添加、读取、遍历、更新和删除等方面。
第四部分将通过三个实际应用场景,展示protobuf map在不同领域的实际应用,并着重强调其在配置管理系统、学生成绩管理系统和订单处理系统中的价值。
最后,在第五部分中,我们将对全文内容进行总结,并对protobuf map的发展前景和拓展可能性进行展望。
1.3 目的本文的目标是通过详细介绍protobuf map的用法和应用示例,帮助读者全面了解protobuf map在数据管理和传输过程中的优势和具体操作方法。
通过阅读本文,读者将能够掌握protobuf map的核心概念、定义以及使用技巧,进而在实际项目中灵活运用该功能解决相关问题。
以上为文章“1. 引言”部分内容,请根据需要进行调整或添加详细信息。
2. protobuf map 用法的基本介绍:2.1 protobuf基础知识回顾Protobuf,即Protocol Buffers,是一种由Google开发的数据序列化格式。
java groovy表达式Groovy是一种基于Java语言的动态语言,它在语法和特性上与Java非常相似。
Groovy支持许多Java中不存在的新特性,比如闭包、元编程、动态类型等。
在Groovy中,表达式是程序中用于执行计算或产生值的代码片段。
在Groovy中,表达式可以出现在各种地方,比如赋值语句、条件语句、循环语句等。
以下是一些Groovy中常见的表达式示例:1. 算术表达式:```groovydef a = 10def b = 5def c = a + bprintln(c) // 输出15```在这个例子中,`a`和`b`是变量,`a + b`是一个算术表达式,将`a`和`b`相加得到结果`15`。
2. 逻辑表达式:```groovydef x = 10def y = 5def z = x > yprintln(z) // 输出true```在这个例子中,`x > y`是一个比较表达式,比较`x`和`y`的大小,结果为`true`。
3. 字符串表达式:```groovydef name = "Alice"def age = 20def message = "My name is ${name} and I am ${age} years old." println(message) // 输出"My name is Alice and I am 20 years old." ```在这个例子中,`${}`是Groovy中的字符串插值表达式,可以在字符串中插入变量的值。
4. 方法调用表达式:```groovydef list = [1, 2, 3, 4, 5]def size = list.size()println(size) // 输出5```在这个例子中,`list.size()`是一个方法调用表达式,调用`list`对象的`size()`方法,并返回结果`5`。
1. 字符串有整型的相互转换Java代码String a = String.valueOf(2); //integer to numeric stringint i = Integer.parseInt(a); //numeric string to an int2. 向文件末尾添加内容Java代码1.BufferedWriter out = null;2.try {3.out = new BufferedWriter(new FileWriter(”filename”, true));4.out.write(”aString”);5.} catch (IOException e) {6.// error processing code7.} finally {8.if (out != null) {9.out.close();10.}11.}复制代码3. 得到当前方法的名字Java代码String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();4. 转字符串到日期Java代码java.util.Date = java.text.DateFormat.getDateInstance().parse(date String);或者是:SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" );Date date = format.parse( myString );5. 使用JDBC链接OracleJava代码1.public class OracleJdbcTest2.{3.String driverClass = "oracle.jdbc.driver.OracleDriver";4.Connection con;5.public void init(FileInputStream fs) throws ClassNotFoundException, SQLException, FileNotFoundException, IOException6.{7.Properties props = new Properties();8.props.load(fs);9.String url = props.getProperty("db.url");10.String userName = props.getProperty("er");11.String password = props.getProperty("db.password");12.Class.forName(driverClass);13.con=DriverManager.getConnection(url, userName, password);14.}15.public void fetch() throws SQLException, IOException16.{17.PreparedStatement ps = con.prepareStatement("select SYSDATE from dual");18.ResultSet rs = ps.executeQuery();19.while (rs.next())20.{21.// do the thing you do22.}23.rs.close();24.ps.close();25.}26.public static void main(String[] args)27.{28.OracleJdbcTest test = new OracleJdbcTest();29.test.init();30.test.fetch();31.}32.}复制代码6. 把Java util.Date 转成sql.DateJava代码java.util.Date utilDate = new java.util.Date();java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());7. 使用NIO进行快速的文件拷贝Java代码1.public static void fileCopy( File in, File out )2.throws IOException3.{4.FileChannel inChannel = new FileInputStream( in ).getChannel();5.FileChannel outChannel = new FileOutputStream( out ).getChannel();6.try7.{8.// inChannel.transferTo(0, inChannel.size(), outChannel); // original -- apparently has trouble copying large fileson Windows9.// magic number for Windows, 64Mb - 32Kb)10.int maxCount = (64 * 1024 * 1024) - (32 * 1024);11.long size = inChannel.size();12.long position = 0;13.while ( position < size )14.{15.position += inChannel.transferTo( position, maxCount, outChannel );16.}17.}18.finally19.{20.if ( inChannel != null )21.{22.inChannel.close();23.}24.if ( outChannel != null )25.{26.outChannel.close();27.}28.}29.}复制代码8. 创建图片的缩略图Java代码1.private void createThumbnail(String filename, int thumbWidth, int thumbHeight, int quality, String outFilename)2.throws InterruptedException, FileNotFoundException, IOException3.{4.// load image from filename5.Image image = Toolkit.getDefaultToolkit().getImage(filename);6.MediaTracker mediaTracker = new MediaTracker(new Container());7.mediaTracker.addImage(image, 0);8.mediaTracker.waitForID(0);9.// use this to test for errors at this point: System.out.println(mediaTracker.isErrorAny());10.// determine thumbnail size from WIDTH and HEIGHT11.double thumbRatio = (double)thumbWidth / (double)thumbHeight;12.int imageWidth = image.getWidth(null);13.int imageHeight = image.getHeight(null);14.double imageRatio = (double)imageWidth / (double)imageHeight;15.if (thumbRatio < imageRatio) {16.thumbHeight = (int)(thumbWidth / imageRatio);17.} else {18.thumbWidth = (int)(thumbHeight * imageRatio);19.}20.// draw original image to thumbnail image object and21.// scale it to the new size on-the-fly22.BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);23.Graphics2D graphics2D = thumbImage.createGraphics();24.graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);25.graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);26.// save thumbnail image to outFilename27.BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename));28.JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);29.JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);30.quality = Math.max(0, Math.min(quality, 100));31.param.setQuality((float)quality / 100.0f, false);32.encoder.setJPEGEncodeParam(param);33.encoder.encode(thumbImage);34.out.close();35.}复制代码9. 创建JSON 格式的数据Java代码1.import org.json.JSONObject;2....3....4.JSONObject json = new JSONObject();5.json.put("city", "Mumbai");6.json.put("country", "India");7....8.String output = json.toString();9....复制代码10. 使用iText JAR生成PDFJava代码阅读这篇文章了解更多细节1.import java.io.File;2.import java.io.FileOutputStream;3.import java.io.OutputStream;4.import java.util.Date;5.import com.lowagie.text.Document;6.import com.lowagie.text.Paragraph;7.import com.lowagie.text.pdf.PdfWriter;8.public class GeneratePDF {9.public static void main(String[] args) {10.try {11.OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));12.Document document = new Document();13.PdfWriter.getInstance(document, file);14.document.open();15.document.add(new Paragraph("Hello Kiran"));16.document.add(new Paragraph(new Date().toString()));17.document.close();18.file.close();19.} catch (Exception e) {20. e.printStackTrace();21.}22.}23.}复制代码11. HTTP 代理设置Java代码1.System.getProperties().put("http.proxyHost", "someProxyURL");2.System.getProperties().put("http.proxyPort", "someProxyPort");3.System.getProperties().put("http.proxyUser", "someUserName");4.System.getProperties().put("http.proxyPassword", "somePassword"); 复制代码12. 单实例Singleton 示例Java代码1.public class SimpleSingleton {2.private static SimpleSingleton singleInstance = new SimpleSingleton();3.//Marking default constructor private4.//to avoid direct instantiation.5.private SimpleSingleton() {6.}7.//Get instance for class SimpleSingleton8.public static SimpleSingleton getInstance() {9.return singleInstance;10.}11.}复制代码另一种实现1.public enum SimpleSingleton {2.INSTANCE;3.public void doSomething() {4.}5.}6.//Call the method from Singleton:7.SimpleSingleton.INSTANCE.doSomething();复制代码13. 抓屏程序Java代码1.import java.awt.Dimension;2.import java.awt.Rectangle;3.import java.awt.Robot;4.import java.awt.Toolkit;5.import java.awt.image.BufferedImage;6.import javax.imageio.ImageIO;7.import java.io.File;8....9.public void captureScreen(String fileName) throws Exception {10.Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();11.Rectangle screenRectangle = new Rectangle(screenSize);12.Robot robot = new Robot();13.BufferedImage image = robot.createScreenCapture(screenRectangle);14.ImageIO.write(image, "png", new File(fileName));15.}16....17.18.import java.awt.Dimension;19.import java.awt.Rectangle;20.import java.awt.Robot;21.import java.awt.Toolkit;22.import java.awt.image.BufferedImage;23.import javax.imageio.ImageIO;24.import java.io.File;25....26.public void captureScreen(String fileName) throws Exception {27.Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();28.Rectangle screenRectangle = new Rectangle(screenSize);29.Robot robot = new Robot();30.BufferedImage image = robot.createScreenCapture(screenRectangle);31.ImageIO.write(image, "png", new File(fileName));32.}复制代码14. 列出文件和目录Java代码1.File dir = new File("directoryName");2.String[] children = dir.list();3.if (children == null) {4.// Either dir does not exist or is not a directory5.} else {6.for (int i=0; i < children.length; i++) {7.// Get filename of file or directory8.String filename = children[i];9.}10.}11.// It is also possible to filter the list of returned files.12.// This example does not return any files that start with `.'.13.FilenameFilter filter = new FilenameFilter() {14.public boolean accept(File dir, String name) {15.return !name.startsWith(".");16.}17.};18.children = dir.list(filter);19.// The list of files can also be retrieved as File objects20.File[] files = dir.listFiles();21.// This filter only returns directories22.FileFilter fileFilter = new FileFilter() {23.public boolean accept(File file) {24.return file.isDirectory();25.}26.};27.files = dir.listFiles(fileFilter);复制代码15. 创建ZIP和JAR文件Java代码1.import java.util.zip.*;2.import java.io.*;3.public class ZipIt {4.public static void main(String args[]) throws IOException {5.if (args.length < 2) {6.System.err.println("usage: java ZipIt Zip.zip file1 file2 file3");7.System.exit(-1);8.}9.File zipFile = new File(args[0]);10.if (zipFile.exists()) {11.System.err.println("Zip file already exists, please try another");12.System.exit(-2);13.}14.FileOutputStream fos = new FileOutputStream(zipFile);15.ZipOutputStream zos = new ZipOutputStream(fos);16.int bytesRead;17.byte[] buffer = new byte[1024];18.CRC32 crc = new CRC32();19.for (int i=1, n=args.length; i < n; i++) {20.String name = args[i];21.File file = new File(name);22.if (!file.exists()) {23.System.err.println("Skipping: " + name);24.continue;25.}26.BufferedInputStream bis = new BufferedInputStream(27.new FileInputStream(file));28.crc.reset();29.while ((bytesRead = bis.read(buffer)) != -1) {30.crc.update(buffer, 0, bytesRead);31.}32.bis.close();33.// Reset to beginning of input stream34.bis = new BufferedInputStream(35.new FileInputStream(file));36.ZipEntry entry = new ZipEntry(name);37.entry.setMethod(ZipEntry.STORED);38.entry.setCompressedSize(file.length());39.entry.setSize(file.length());40.entry.setCrc(crc.getValue());41.zos.putNextEntry(entry);42.while ((bytesRead = bis.read(buffer)) != -1) {43.zos.write(buffer, 0, bytesRead);44.}45.bis.close();46.}47.zos.close();48.}49.}复制代码16. 解析/读取XML 文件Java代码1.XML文件2.<?xml version="1.0"?>3.<students>4.<student>5.<name>John</name>6.<grade>B</grade>7.<age>12</age>8.</student>9.<student>10.<name>Mary</name>11.<grade>A</grade>12.<age>11</age>13.</student>14.<student>15.<name>Simon</name>16.<grade>A</grade>17.<age>18</age>18.</student>19.</students>复制代码Java代码1.package net.viralpatel.java.xmlparser;2.import java.io.File;3.import javax.xml.parsers.DocumentBuilder;4.import javax.xml.parsers.DocumentBuilderFactory;5.import org.w3c.dom.Document;6.import org.w3c.dom.Element;7.import org.w3c.dom.Node;8.import org.w3c.dom.NodeList;9.public class XMLParser {10.public void getAllUserNames(String fileName) {11.try {12.DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();13.DocumentBuilder db = dbf.newDocumentBuilder();14.File file = new File(fileName);15.if (file.exists()) {16.Document doc = db.parse(file);17.Element docEle = doc.getDocumentElement();18.// Print root element of the document19.System.out.println("Root element of the document: "20.+ docEle.getNodeName());21.NodeList studentList = docEle.getElementsByTagName("student");22.// Print total student elements in document23.System.out24..println("Total students: " + studentList.getLength());25.if (studentList != null && studentList.getLength() > 0) {26.for (int i = 0; i < studentList.getLength(); i++) {27.Node node = studentList.item(i);28.if (node.getNodeType() == Node.ELEMENT_NODE) {29.System.out.println("=====================");30.Element e = (Element) node;31.NodeList nodeList = e.getElementsByTagName("name");32.System.out.println("Name: "33.+ nodeList.item(0).getChildNodes().item(0)34..getNodeValue());35.nodeList = e.getElementsByTagName("grade");36.System.out.println("Grade: "37.+ nodeList.item(0).getChildNodes().item(0)38..getNodeValue());39.nodeList = e.getElementsByTagName("age");40.System.out.println("Age: "41.+ nodeList.item(0).getChildNodes().item(0)42..getNodeValue());43.}44.}45.} else {46.System.exit(1);47.}48.}49.} catch (Exception e) {50.System.out.println(e);51.}52.}53.public static void main(String[] args) {54.XMLParser parser = new XMLParser();55.parser.getAllUserNames("c:\\test.xml");56.}57.}复制代码17. 把Array 转换成MapJava代码1.import java.util.Map;2.import ng.ArrayUtils;3.public class Main {4.public static void main(String[] args) {5.String[][] countries = { { "United States", "New York" }, { "United Kingdom", "London" },6.{ "Netherland", "Amsterdam" }, { "Japan", "Tokyo" }, { "France", "Paris" } };7.Map countryCapitals = ArrayUtils.toMap(countries);8.System.out.println("Capital of Japan is " + countryCapitals.get("Japan"));9.System.out.println("Capital of France is " + countryCapitals.get("France"));10.}11.}复制代码18. 发送邮件Java代码1.import javax.mail.*;2.import javax.mail.internet.*;3.import java.util.*;4.public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingException5.{6.boolean debug = false;7.//Set the host smtp address8.Properties props = new Properties();9.props.put("mail.smtp.host", "");10.// create some properties and get the default Session11.Session session = Session.getDefaultInstance(props, null);12.session.setDebug(debug);13.// create a message14.Message msg = new MimeMessage(session);15.// set the from and to address16.InternetAddress addressFrom = new InternetAddress(from);17.msg.setFrom(addressFrom);18.InternetAddress[] addressTo = new InternetAddress[recipients.length];19.for (int i = 0; i < recipients.length; i++)20.{21.addressTo[i] = new InternetAddress(recipients[i]);22.}23.msg.setRecipients(Message.RecipientType.TO, addressTo);24.// Optional : You can also set your custom headers in the Email if you Want25.msg.addHeader("MyHeaderName", "myHeaderValue");26.// Setting the Subject and Content Type27.msg.setSubject(subject);28.msg.setContent(message, "text/plain");29.Transport.send(msg);30.}复制代码19. 发送代数据的HTTP 请求Java代码1.import java.io.BufferedReader;2.import java.io.InputStreamReader;3.import .URL;4.public class Main {5.public static void main(String[] args) {6.try {7.URL my_url = new URL("/");8.BufferedReader br = new BufferedReader(new InputStreamReader(my_url.openStream()));9.String strTemp = "";10.while(null != (strTemp = br.readLine())){11.System.out.println(strTemp);12.}13.} catch (Exception ex) {14.ex.printStackTrace();15.}16.}17.}复制代码20. 改变数组的大小Java代码查看源代码打印帮助1./**2.* Reallocates an array with a new size, and copies the contents3.* of the old array to the new array.4.* @param oldArray the old array, to be reallocated.5.* @param newSize the new array size.6.* @return A new array with the same contents.7.*/8.private static Object resizeArray (Object oldArray, int newSize) {9.int oldSize = ng.reflect.Array.getLength(oldArray);10.Class elementType = oldArray.getClass().getComponentType();11.Object newArray = ng.reflect.Array.newInstance(12.elementType,newSize);13.int preserveLength = Math.min(oldSize,newSize);14.if (preserveLength > 0)15.System.arraycopy (oldArray,0,newArray,0,preserveLength);16.return newArray;17.}18.// Test routine for resizeArray().19.public static void main (String[] args) {20.int[] a = {1,2,3};21. a = (int[])resizeArray(a,5);22.a[3] = 4;23.a[4] = 5;24.for (int i=0; i<a.length; i++)25.System.out.println (a[i]);26.}复制代码。