JAVA实例

环境数设置实例

如何编译 Java 文件

本文我们演示如何编译 HelloWorld.java 文件,其中 Java 代码如下 -

public class HelloWorld {
	public static void main(String []args) {
	   System.out.println("Hello World");
	}
}

接下来我们使用 javac 命令来编译 Java 文件,并使用 java 命令执行编译的文件

c:\jdk> javac HelloWorld.java
c:\jdk> java HelloWorld

以上代码实例输出结果为 -

Hello World

如何执行指定class文件目录(classpath)

如果我们 Java 编译后的class文件不在当前目录,我们可以使用 -classpath 来指定class文件目录 -

C:> java -classpath C:\java\DemoClasses HelloWorld

以上命令中我们使用了 -classpath 参数指定了 HelloWorld 的 class 文件所在目录。

如果class文件在jar文件中,则命令如下 -

c:> java -classpath C:\java\myclasses.jar

如何查看当前 Java 运行的版本?

我们可以使用 -version 参数来查看当前 Java 的运行版本,命令如下-

java -version

以上代码实例输出结果为 -

java version "1.6.0_13"
Java(TM) SE Runtime Environment (build 1.6.0_13-b03)
Java HotSpot(TM) Client VM (build 11.3-b02, mixed mode, sharing)

字符串

字符串比较

以下实例中我们通过字符串函数 compareTo (string) ,compareToIgnoreCase(String) 及 compareTo(object string) 来比较两个字符串,并返回字符串中第一个字母ASCII的差值。

public class StringCompareEmp{
   public static void main(String args[]){
	  String str = "Hello World";
	  String anotherString = "hello world";
	  Object objStr = str;
 
	  System.out.println( str.compareTo(anotherString) );
	  System.out.println( str.compareToIgnoreCase(anotherString) );  
	  System.out.println( str.compareTo(objStr.toString()));
   }
}

以上代码实例输出结果为 -

-32
0
0

查找字符串最后一次出现的位置

以下实例中我们通过字符串函数 strOrig.lastIndexOf(Stringname) 来查找子字符串 Stringname 在 strOrig 出现的位置 -

public class SearchlastString {
   public static void main(String[] args) {
	  String strOrig = "Hello world ,Hello Reader";
	  int lastIndex = strOrig.lastIndexOf("Hello");
	  
	  if(lastIndex == - 1){
		 System.out.println("Hello not found");
	  } else {
		 System.out.println("Last occurrence of Hello is at index "+ lastIndex);
	  }
   }
}

以上代码实例输出结果为 -

Last occurrence of Hello is at index 13

删除字符串中的一个字符

以下实例中我们通过字符串函数 substring() 函数来删除字符串中的一个字符,我们将功能封装在 removeCharAt 函数中。

public class Main {
   public static void main(String args[]) {
	  String str = "this is Java";
	  System.out.println(removeCharAt(str, 3));
   }
   public static String removeCharAt(String s, int pos) {
	  return s.substring(0, pos) + s.substring(pos + 1);
   }
}

以上代码实例输出结果为 -

thi is Java

字符串替换

如何使用java替换字符串中的字符呢?以下实例中我们使用 java String 类的 replace 方法来替换字符串中的字符 -

public class StringReplaceEmp{
   public static void main(String args[]){
	  String str="Hello World";
	  System.out.println( str.replace( 'H','W' ) );
	  System.out.println( str.replaceFirst("He", "Wa") );
	  System.out.println( str.replaceAll("He", "Ha") );
   }
}

以上代码实例输出结果为 -

Wello World
Wallo World
Hallo World

字符串反转

以下实例演示了如何使用 Java 的反转函数 reverse() 将字符串反转 -

public class StringReverseExample{
   public static void main(String[] args){
	  String string="java";
	  String reverse = new StringBuffer(string).reverse().toString();
	  System.out.println("before:"+string);
	  System.out.println("after:"+reverse);
   }
}

以上代码实例输出结果为 -

before:java
after:avaj

字符串搜索

以下实例使用了 String 类的 indexOf() 方法在字符串中查找子字符串出现的位置,如果存在返回字符串出现的位置(第一位为0),如果不存在返回 -1 -

public class SearchStringEmp{
   public static void main(String[] args) {
	  String strOrig = "Hello readers";
	  int intIndex = strOrig.indexOf("Hello");
	  
	  if(intIndex == - 1) {
		 System.out.println("Hello not found");
	  } else {
		 System.out.println("Found Hello at index " + intIndex);
	  }
   }
}

以上代码实例输出结果为 -

Found Hello at index 0

字符串分割

以下实例使用了 split(string) 方法通过指定分隔符将字符串分割为数组 -

public class JavaStringSplitEmp{
	public static void main(String args[]) {
		String str = "jan-feb-march";
		String[] temp;
		String delimeter = "-";
		temp = str.split(delimeter);
	
		for(int i = 0; i < temp.length; i++) {
			System.out.println(temp[i]);
			System.out.println("");
			str = "jan.feb.march";
			delimeter = "\\.";
			temp = str.split(delimeter);
		}
		for(int i =0; i < temp.length; i++) {
			System.out.println(temp[i]);
			System.out.println("");
			temp = str.split(delimeter,2);
	
			for(int j = 0; j < temp.length; j++){
				System.out.println(temp[j]);
			}
		}
	}
}

以上代码实例输出结果为 -

jan

feb

march

jan

jan
feb.march
feb.march

jan
feb.march

字符串小写转大写

以下实例使用了 String toUpperCase() 方法将字符串从小写转为大写

public class StringToUpperCaseEmp {
	public static void main(String[] args) {
		String str = "string java";
		String strUpper = str.toUpperCase();
		System.out.println("before: " + str);
		System.out.println("after: " + strUpper);
	}
}

以上代码实例输出结果为 -

before: string java
after: STRING JAVA

测试两个字符串区域是否相等

以下示例使用regionMatches()方法确定两个字符串中的区域匹配。

public class StringRegionMatch {
   public static void main(String[] args) {
	  String first_str = "Welcome to Microsoft";
	  String second_str = "I work with Microsoft";
	  boolean match = first_str.regionMatches(11, second_str, 12, 9);
	  System.out.println("first_str[11 -19] == " + "second_str[12 - 21]:-"+ match);
   }
}
  • 11是比较开始的源字符串中的索引号
  • Second_str是目标字符串
  • 12是比较应从目标字符串开始的索引号
  • 9是要比较的字符数

以上代码实例输出结果为 -

first_str[11 -19] == second_str[12 - 21]:-true 

字符串性能比较

以下示例比较了以两种不同方式创建的两个字符串的性能。

public class StringComparePerformance {
   public static void main(String[] args) {      
	  long startTime = System.currentTimeMillis();
	  
	  for(int i=0;i<50000;i++) {
		 String s1 = "hello";
		 String s2 = "hello"; 
	  }
	  long endTime = System.currentTimeMillis();
	  System.out.println("Time taken for creation" 
		 + " of String literals : "+ (endTime - startTime) 
		 + " milli seconds" );       
	  long startTime1 = System.currentTimeMillis();
	  
	  for(int i=0;i<50000;i++) {
		 String s3 = new String("hello");
		 String s4 = new String("hello");
	  }
	  long endTime1 = System.currentTimeMillis();
	  System.out.println("Time taken for creation" 
		 + " of String objects : " + (endTime1 - startTime1)
		 + " milli seconds");
   }
}

以上代码实例输出结果为 -

Time taken for creation of String literals : 0 milli seconds
Time taken for creation of String objects : 16 milli seconds

字符串优化

以下示例使用String.intern()方法优化了字符串创建。

public class StringOptimization {
	public static void main(String[] args) {
		String variables[] = new String[50000];
		for( int i = 0;i <50000;i++) {
			variables[i] = "s"+i;
		}
		long startTime0 = System.currentTimeMillis();
	
		for(int i = 0;i<50000;i++) {
			variables[i] = "hello";
		}
		long endTime0 = System.currentTimeMillis();
		System.out.println("Creation time"
			+ " of String literals : "+ (endTime0 - startTime0)
			+ " ms" );
		long startTime1 = System.currentTimeMillis();
	
		for(int i = 0;i<50000;i++) {
			variables[i] = new String("hello");
		}
		long endTime1 = System.currentTimeMillis();
		System.out.println("Creation time of"
			+ " String objects with 'new' key word : "
			+ (endTime1 - startTime1)
			+ " ms");
		long startTime2 = System.currentTimeMillis();
	
		for(int i = 0;i<50000;i++) {
			variables[i] = new String("hello");
			variables[i] = variables[i].intern();
		}
		long endTime2 = System.currentTimeMillis();
		System.out.println("Creation time of"
			+ " String objects with intern(): "
			+ (endTime2 - startTime2)
			+ " ms");
	}
}

以上代码实例输出结果为 -

Creation time of String literals : 0 ms
Creation time of String objects with 'new' key word : 31 ms
Creation time of String objects with intern(): 16 ms

字符串格式化

以下示例通过在format()方法中使用特定区域设置,格式和参数来返回格式化的字符串值

import java.util.*;

public class StringFormat{
   public static void main(String[] args){
	  double e = Math.E;
	  System.out.format("%f%n", e);
	  System.out.format(Locale.GERMANY, "%-10.4f%n%n", e);
   }
}

以上代码实例输出结果为 -

2.718282
2,7183   

连接字符串

以下示例通过使用“+”运算符和StringBuffer.append()方法显示了连接的性能。

public class StringConcatenate {
   public static void main(String[] args) {
	  long startTime = System.currentTimeMillis();
	  
	  for(int i = 0;i < 5000;i++) {
		 String result = "This is"
			+ "testing the"
			+ "difference"+ "between"
			+ "String"+ "and"+ "StringBuffer";
	  }
	  long endTime = System.currentTimeMillis();
	  System.out.println("Time taken for string" 
		 + "concatenation using + operator : " 
		 + (endTime - startTime)+ " ms");
	  long startTime1 = System.currentTimeMillis();
	  
	  for(int i = 0;i < 5000;i++) {
		 StringBuffer result = new StringBuffer();
		 result.append("This is");
		 result.append("testing the");
		 result.append("difference");
		 result.append("between");
		 result.append("String");
		 result.append("and");
		 result.append("StringBuffer");
	  }
	  long endTime1 = System.currentTimeMillis();
	  System.out.println("Time taken for String concatenation" 
		 + "using StringBuffer : "
		 + (endTime1 - startTime1)+ " ms");
   }
}

以上代码实例输出结果为 -

Time taken for stringconcatenation using + operator : 0 ms
Time taken for String concatenationusing StringBuffer : 22 ms

字符串缓冲

以下示例缓冲字符串,并使用emit()方法刷新它。

public class StringBuffer {
   public static void main(String[] args) {
	  countTo_N_Improved();
   }
   private final static int MAX_LENGTH = 30;
   private static String buffer = "";
   
   private static void emit(String nextChunk) {
	  if(buffer.length() + nextChunk.length() > MAX_LENGTH) {
		 System.out.println(buffer);
		 buffer = "";  
	  }
	  buffer += nextChunk;
   }
   private static final int N = 100;
   private static void countTo_N_Improved() {
	  for (int count = 2; count <= N; count = count+2) {
		 emit(" " + count);
	  }
   }
}

上面的代码示例将产生以下结果 -

2 4 6 8 10 12 14 16 18 20 22
24 26 28 30 32 34 36 38 40 42
44 46 48 50 52 54 56 58 60 62
64 66 68 70 72 74 76 78 80 82

StringBuffer和StringBuilder类用于创建可变字符串。

public class HelloWorld {
   public static void main(String []args) {
	  StringBuffer sb = new StringBuffer("hello");
	  sb.append("world");
	  sb.insert(0, " Tutorialspoint");
	  System.out.print(sb);
   }
}

上面的代码示例将产生以下结果 -

Tutorialspointhelloworld

数组

数组排序和搜索

以下示例显示如何使用sort()和binarySearch()方法来完成任务。 用户定义的方法printArray()用于显示输出 -

import java.util.Arrays;
	
public class MainClass {
	public static void main(String args[]) throws Exception {
		int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
		Arrays.sort(array);
		printArray("Sorted array", array);
		int index = Arrays.binarySearch(array, 2);
		System.out.println("Found 2 @ " + index);
	}
	private static void printArray(String message, int array[]) {
		System.out.println(message + ": [length: " + array.length + "]");
	
		for (int i = 0; i < array.length; i++) {
			if(i != 0) {
				System.out.print(", ");
			}
			System.out.print(array[i]);
		}
		System.out.println();
	}
}

上面的代码示例将产生以下结果。

Sorted array: [length: 10]
-9, -7, -3, -2, 0, 2, 4, 5, 6, 8
Found 2 @ 5

数组排序和插入

以下示例显示如何使用sort()方法和用户定义的方法insertElement()来完成任务。

import java.util.Arrays;

public class MainClass {
   public static void main(String args[]) throws Exception {
	  int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
	  Arrays.sort(array);
	  printArray("Sorted array", array);
	  
	  int index = Arrays.binarySearch(array, 1);
	  System.out.println("Didn't find 1 @ " + index);
	  
	  int newIndex = -index - 1;
	  array = insertElement(array, 1, newIndex);
	  printArray("With 1 added", array);
   }
   private static void printArray(String message, int array[]) {
	  System.out.println(message + ": [length: " + array.length + "]");
	  for (int i = 0; i < array.length; i++) {
		 if (i != 0){
			System.out.print(", ");
		 }
		 System.out.print(array[i]);         
	  }
	  System.out.println();
   }
   private static int[] insertElement(int original[], int element, int index) {
	  int length = original.length;
	  int destination[] = new int[length + 1];
	  System.arraycopy(original, 0, destination, 0, index);
	  destination[index] = element;
	  System.arraycopy(original, index, destination, index + 1, length - index);
	  return destination;
   }
}

上面的代码示例将产生以下结果。

Sorted array: [length: 10]
-9, -7, -3, -2, 0, 2, 4, 5, 6, 8
Didn't find 1 @ -6
With 1 added: [length: 11]
-9, -7, -3, -2, 0, 1, 2, 4, 5, 6, 8

数组的维数

以下示例有助于使用arrayname.length确定二维数组的上限。

public class Main {
   public static void main(String args[]) {
	  String[][] data = new String[2][5];
	  System.out.println("Dimension 1: " + data.length);
	  System.out.println("Dimension 2: " + data[0].length);
   }
}

上面的代码示例将产生以下结果。

Dimension 1: 2
Dimension 2: 5

反转数组

以下示例使用Collections.reverse(ArrayList)方法反转数组列表。

import java.util.ArrayList;
import java.util.Collections;

public class Main {
   public static void main(String[] args) {
	  ArrayList arrayList = new ArrayList();
	  arrayList.add("A");
	  arrayList.add("B");
	  arrayList.add("C");
	  arrayList.add("D");
	  arrayList.add("E");
	  System.out.println("Before Reverse Order: " + arrayList);
	  Collections.reverse(arrayList);
	  System.out.println("After Reverse Order: " + arrayList);
   }
}

上面的代码示例将产生以下结果。

Before Reverse Order: [A, B, C, D, E]
After Reverse Order: [E, D, C, B, A]

数组输出

以下示例演示了通过循环将数组的元素写入输出控制台。

public class Welcome {
   public static void main(String[] args) {
	  String[] greeting = new String[3];
	  greeting[0] = "This is the greeting";
	  greeting[1] = "for all the readers from";
	  greeting[2] = "Java Source .";
	  
	  for (int i = 0; i < greeting.length; i++){
		 System.out.println(greeting[i]);
	  }
   }
}

上面的代码示例将产生以下结果。

This is the greeting
For all the readers From
Java source .

搜索数组最小和最大值

此示例显示如何使用Collection类的Collection.max()和Collection.min()方法搜索数组中的最小和最大元素。

import java.util.Arrays;
import java.util.Collections;

public class Main {
   public static void main(String[] args) {
	  Integer[] numbers = { 8, 2, 7, 1, 4, 9, 5};
	  int min = (int) Collections.min(Arrays.asList(numbers));
	  int max = (int) Collections.max(Arrays.asList(numbers));
	  
	  System.out.println("Min number: " + min);
	  System.out.println("Max number: " + max);
   }
}

上面的代码示例将产生以下结果。

Min number: 1
Max number: 9

数组合并

这个例子展示了如何通过使用list.Addall(Array1.asList(array2)方法的List类和Array类的Arrays.toString()方法将两个数组合并到单个数组中。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
   public static void main(String args[]) {
	  String a[] = { "A", "E", "I" };
	  String b[] = { "O", "U" };
	  List list = new ArrayList(Arrays.asList(a));
	  list.addAll(Arrays.asList(b));
	  Object[] c = list.toArray();
	  System.out.println(Arrays.toString(c));
   }
}

上面的代码示例将产生以下结果。

[A, E, I, O, U]

数组填充

本示例使用Java Util类的Array.fill(arrayname,value)方法和Array.fill(arrayname,starting index,ending index,value)方法填充(初始化数组中的所有元素)数组。

import java.util.*;

public class FillTest {
   public static void main(String args[]) {
	  int array[] = new int[6];
	  Arrays.fill(array, 100);
	  
	  for (int i = 0, n = array.length; i < n; i++) {
		 System.out.println(array[i]);
	  }
	  System.out.println();
	  Arrays.fill(array, 3, 6, 50);
	  
	  for (int i = 0, n = array.length; i < n; i++) {
		 System.out.println(array[i]);
	  }
   }
}

上面的代码示例将产生以下结果。

100
100
100
100
100
100

100
100
100
50
50
50

扩展数组

以下示例显示了如何在初始化后通过创建新数组来扩展数组。

public class Main {
   public static void main(String[] args) {
	  String[] names = new String[] { "A", "B", "C" };
	  String[] extended = new String[5];
	  extended[3] = "D";
	  extended[4] = "E";
	  System.arraycopy(names, 0, extended, 0, names.length);
	  
	  for (String str : extended){
		 System.out.println(str);
	  }
   }
}

上面的代码示例将产生以下结果。

A
B
C
D
E

删除数组元素

以下示例显示如何从数组中删除元素。

import java.util.ArrayList;

public class Main {
   public static void main(String[] args) {
	  ArrayList objArray = new ArrayList();
	  objArray.clear();
	  objArray.add(0,"0th element");
	  objArray.add(1,"1st element");
	  objArray.add(2,"2nd element");
	  System.out.println("Array before removing an element"+objArray);
	  objArray.remove(1);
	  objArray.remove("0th element");
	  System.out.println("Array after removing an element"+objArray);
   }
}

上面的代码示例将产生以下结果。

Array before removing an  element[0th element, 1st element, 2nd element]
Array after removing an element[2nd element]

数组差集

以下示例使用Removeall方法从另一个数组中删除一个数组。

import java.util.ArrayList;

public class Main {
   public static void main(String[] args)  {
	  ArrayList objArray = new ArrayList();
	  ArrayList objArray2 = new ArrayList();
	  objArray2.add(0,"common1");
	  objArray2.add(1,"common2");
	  objArray2.add(2,"notcommon");
	  objArray2.add(3,"notcommon1");
	  objArray.add(0,"common1");
	  objArray.add(1,"common2");
	  objArray.add(2,"notcommon2");
	  System.out.println("Array elements of array1" +objArray);
	  System.out.println("Array elements of array2" +objArray2);
	  objArray.removeAll(objArray2);
	  System.out.println("Array1 after removing array2 from array1"+objArray);
   }
}

上面的代码示例将产生以下结果。

Array elements of array1[common1, common2, notcommon2]
Array elements of array2[common1, common2, notcommon, notcommon1]
Array1 after removing array2 from array1[notcommon2]

数组交集

以下示例显示如何从两个数组中找到公共元素并将它们存储在一个数组中。

import java.util.ArrayList;

public class NewClass {
   public static void main(String[] args) {
	  ArrayList objArray = new ArrayList();
	  ArrayList objArray2 = new ArrayList();
	  objArray2.add(0,"common1");
	  objArray2.add(1,"common2");
	  objArray2.add(2,"notcommon");
	  objArray2.add(3,"notcommon1");
	  objArray.add(0,"common1");
	  objArray.add(1,"common2");
	  objArray.add(2,"notcommon2");
	  System.out.println("Array elements of array1"+objArray);
	  System.out.println("Array elements of array2"+objArray2);
	  objArray.retainAll(objArray2);
	  System.out.println("Array1 after retaining common elements of array2 & array1"+objArray);
   }
}

上面的代码示例将产生以下结果。

Array elements of array1[common1, common2, notcommon2]
Array elements of array2[common1, common2, notcommon,
notcommon1]
Array1 after retaining common elements of array2 & array1
[common1, common2]

在Array中查找对象

以下示例使用Contains方法搜索数组中的字符串。

import java.util.ArrayList;
	
public class Main {
	public static void main(String[] args) {
		ArrayList objArray = new ArrayList();
		ArrayList objArray2 = new ArrayList();
		objArray2.add(0,"common1");
		objArray2.add(1,"common2");
		objArray2.add(2,"notcommon");
		objArray2.add(3,"notcommon1");
		objArray.add(0,"common1");
		objArray.add(1,"common2");
		System.out.println("Array elements of array1"+objArray);
		System.out.println("Array elements of array2"+objArray2);
		System.out.println("Array 1 contains String common2?? "
			+objArray.contains("common1"));
		System.out.println("Array 2 contains Array1?? "
			+objArray2.contains(objArray));
	}
}

上面的代码示例将产生以下结果。

Array elements of array1[common1, common2]
Array elements of array2[common1, common2, notcommon, notcommon1]
Array 1 contains String common2?? true
Array 2 contains Array1?? false

判断数组是否相等

下面的例子展示了如何使用Arrays的equals()方法来检查两个数组是否相等。

import java.util.Arrays;

public class Main {
   public static void main(String[] args) throws Exception {
	  int[] ary = {1,2,3,4,5,6};
	  int[] ary1 = {1,2,3,4,5,6};
	  int[] ary2 = {1,2,3,4};
	  System.out.println("Is array 1 equal to array 2?? " +Arrays.equals(ary, ary1));
	  System.out.println("Is array 1 equal to array 3?? " +Arrays.equals(ary, ary2));
   }
}

上面的代码示例将产生以下结果。

Is array 1 equal to array 2?? true
Is array 1 equal to array 3?? false

时间处理

格式化时间(SimpleDateFormat)

以下实例演示了如何使用 SimpleDateFormat 类的 format(date) 方法来格式化时间

import java.text.SimpleDateFormat;
import java.util.Date;
 
public class Main{
	public static void main(String[] args){
		Date date = new Date();
		String strDateFormat = "yyyy-MM-dd HH:mm:ss";
		SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
		System.out.println(sdf.format(date));
	}
}

以上代码运行输出结果为

2018-03-27 21:13:23

获取当前时间

以下实例演示了如何使用 Date 类及 SimpleDateFormat 类的 format(date) 方法来输出当前时间

import java.text.SimpleDateFormat;
import java.util.Date;
 
public class Main{
	public static void main(String[] args){
		
		SimpleDateFormat sdf = new SimpleDateFormat();
		sdf.applyPattern("yyyy-MM-dd HH:mm:ss a");  
		Date date = new Date(); 
		System.out.println("Now Time:" + sdf.format(date)); 
	} 
}

以上代码运行输出结果为

Now Time:2015-03-27 21:27:28 PM

时间戳转换成时间

以下实例演示了如何使用 SimpleDateFormat 类的 format() 方法将时间戳转换成时间

import java.text.SimpleDateFormat;
import java.util.Date;
 
public class Main{
	public static void main(String[] args){
		Long timeStamp = System.currentTimeMillis();  
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		String sd = sdf.format(new Date(Long.parseLong(String.valueOf(timeStamp))));   
		System.out.println(sd);
   }
}

以上代码运行输出结果为

2018-03-28

获取年份、月份等

以下实例演示了如何使用 Calendar 类来输出年份、月份等

import java.util.Calendar;
 
public class Main {
	public static void main(String[] args) {
		Calendar cal = Calendar.getInstance();
		int day = cal.get(Calendar.DATE);
		int month = cal.get(Calendar.MONTH) + 1;
		int year = cal.get(Calendar.YEAR);
		int dow = cal.get(Calendar.DAY_OF_WEEK);
		int dom = cal.get(Calendar.DAY_OF_MONTH);
		int doy = cal.get(Calendar.DAY_OF_YEAR);
 
		System.out.println("Time: " + cal.getTime());
		System.out.println("Date: " + day);
		System.out.println("Month: " + month);
		System.out.println("Year: " + year);
		System.out.println("Day of the Week: " + dow); 
		System.out.println("Day of the Month: " + dom);
		System.out.println("Day of the Year: " + doy);
	}
}

以上代码运行输出结果为

Time: Fri Mar 27 21:44:15 CST 2018
Date: 27
Month: 3
Year: 2015
Day of the week: 2
Day of the Month: 27
Day of the Year: 86

方法

方法重载

此示例根据参数的类型和数量显示重载方法的方式。

class MyClass {
   int height;
   MyClass() {
	  System.out.println("bricks");
	  height = 0;
   }
   MyClass(int i) {
	  System.out.println("Building new House that is " + i + " feet tall");
	  height = i;
   }
   void info() {
	  System.out.println("House is " + height + " feet tall");
   }
   void info(String s) {
	  System.out.println(s + ": House is " + height + " feet tall");
   }
}
public class MainClass {
   public static void main(String[] args) {
	  MyClass t = new MyClass(0);
	  t.info();
	  t.info("overloaded method");
	  
	  //Overloaded constructor:
	  new MyClass();
   }
}

上面的代码示例将产生以下结果。

Building new House that is 0 feet tall.
House is 0 feet tall.
Overloaded method: House  is 0 feet tall.
bricks

使用方法打印数组

本示例显示使用重载方法打印数组类型(整数,双精度和字符)的方式。

public class MainClass {
   public static void printArray(Integer[] inputArray) {
	  for (Integer element : inputArray){
		 System.out.printf("%s ", element);
		 System.out.println();
	  }
   }
   public static void printArray(Double[] inputArray) {
	  for (Double element : inputArray){
		 System.out.printf("%s ", element);
		 System.out.println();
	  }
   }
   public static void printArray(Character[] inputArray) {
	  for (Character element : inputArray){
		 System.out.printf("%s ", element);
		 System.out.println();
	  }
   }
   public static void main(String args[]) {
	  Integer[] integerArray = { 1, 2, 3, 4, 5, 6 };
	  Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
	  Character[] characterArray = { 'H', 'E', 'L', 'L', 'O' };
	  
	  System.out.println("Array integerArray contains:");
	  printArray(integerArray);
	  
	  System.out.println("\nArray doubleArray contains:");
	  printArray(doubleArray);
	  
	  System.out.println("\nArray characterArray contains:");
	  printArray(characterArray);
   }
}

上面的代码示例将产生以下结果。

Array integerArray contains:
1 
2 
3 
4 
5 
6 

Array doubleArray contains:
1.1 
2.2 
3.3 
4.4 
5.5 
6.6 
7.7 

Array characterArray contains:
H 
E 
L 
L 
O 

汉诺塔算法

汉诺塔(又称河内塔)问题是源于印度一个古老传说的益智玩具。大梵天创造世界的时候做了三根金刚石柱子,在一根柱子上从下往上按照大小顺序摞着64片黄金圆盘。大梵天命令婆罗门把圆盘从下面开始按大小顺序重新摆放在另一根柱子上。并且规定,在小圆盘上不能放大圆盘,在三根柱子之间一次只能移动一个圆盘。

public class MainClass {
   public static void main(String[] args) {
	  int nDisks = 3;
	  doTowers(nDisks, 'A', 'B', 'C');
   }
   public static void doTowers(int topN, char from, char inter, char to) {
	  if (topN == 1) {
		 System.out.println("Disk 1 from " + from + " to " + to);
	  } else {
		 doTowers(topN - 1, from, to, inter);
		 System.out.println("Disk " + topN + " from " + from + " to " + to);
		 doTowers(topN - 1, inter, from, to);
	  }
   }
}

上面的代码示例将产生以下结果。

Disk 1 from A to C
Disk 2 from A to B
Disk 1 from C to B
Disk 3 from A to C
Disk 1 from B to A
Disk 2 from B to C
Disk 1 from A to C

计算斐波那契数列

这个例子显示了使用方法计算斐波纳契数列的方法。

public class MainClass {
   public static long fibonacci(long number) {
	  if ((number == 0) || (number == 1)) return number;
	  else return fibonacci(number - 1) + fibonacci(number - 2);
   }
   public static void main(String[] args) {
	  for (int counter = 0; counter <= 10; counter++){
		 System.out.printf("Fibonacci of %d is: %d\n", counter, fibonacci(counter));
	  }
   }
}

上面的代码示例将产生以下结果。

Fibonacci of 0 is: 0
Fibonacci of 1 is: 1
Fibonacci of 2 is: 1
Fibonacci of 3 is: 2
Fibonacci of 4 is: 3
Fibonacci of 5 is: 5
Fibonacci of 6 is: 8
Fibonacci of 7 is: 13
Fibonacci of 8 is: 21
Fibonacci of 9 is: 34
Fibonacci of 10 is: 55

阶乘

此示例显示了使用方法计算9的阶乘的方式。

public class MainClass {
   public static void main(String args[]) {
	  for (int counter = 0; counter <= 10; counter++) {
		 System.out.printf("%d! = %d\n", counter, factorial(counter));
	  }
   }
   public static long factorial(long number) {
	  if (number <= 1) return 1;
	  else return number * factorial(number - 1);
   }
}

上面的代码示例将产生以下结果。

0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800

方法覆盖

此示例演示了具有不同数量和类型参数的子类覆盖方法。

public class Findareas {
   public static void main (String []agrs) {
	  Figure f = new Figure(10 , 10);
	  Rectangle r = new Rectangle(9 , 5);
	  Figure figref;
	  figref = f;
	  System.out.println("Area is :"+figref.area());
	  figref = r;
	  System.out.println("Area is :"+figref.area());
   }
}
class Figure {
   double dim1;
   double dim2;
   Figure(double a , double b) {
	  dim1 = a;
	  dim2 = b;
   }
   Double area() {
	  System.out.println("Inside area for figure.");
	  return(dim1*dim2);
   }
}
class Rectangle extends Figure {
   Rectangle(double a, double b) {
	  super(a ,b);
   }
   Double area() {
	  System.out.println("Inside area for rectangle.");
	  return(dim1*dim2);
   }
}

上面的代码示例将产生以下结果。

Inside area for figure.
Area is :100.0
Inside area for rectangle.
Area is :45.0

instanceOf 关键字用法

此示例使displayObjectClass()方法显示在此方法中传递的Object的Class作为参数。

import java.util.ArrayList;
import java.util.Vector;

public class Main { 
   public static void main(String[] args) {
	  Object testObject = new ArrayList();
	  displayObjectClass(testObject);
   }
   public static void displayObjectClass(Object o) {
	  if (o instanceof Vector) System.out.println(
		 "Object was an instance of the class java.util.Vector");
	  else if (o instanceof ArrayList) System.out.println(
		 "Object was an instance of the class java.util.ArrayList");
	  else System.out.println("Object was an instance of the " + o.getClass());
   }
}

上面的代码示例将产生以下结果。

Object was an instance of the class java.util.ArrayList

break 关键字用法

这个例子使用'break'跳出循环。

public class Main {
   public static void main(String[] args) {
	  int[] intary = { 99,12,22,34,45,67,5678,8990 };
	  int no = 5678;
	  int i = 0;
	  boolean found = false;
	  
	  for ( ; i < intary.length; i++) {
		 if (intary[i] == no) {
			found = true;
			break;
		 }
	  }
	  if (found) {
		 System.out.println("Found the no: " + no + " at  index: " + i);
	  } else {
		 System.out.println(no + "not found  in the array");
	  }
   }
}

上面的代码示例将产生以下结果。

Found the no: 5678 at  index: 6

continue 关键字用法

本示例使用continue语句跳出方法中的循环。

public class Main {
   public static void main(String[] args) {
	  StringBuffer searchstr = new StringBuffer(
		 "hello how are you. ");
	  int length = searchstr.length();
	  int count = 0;
	  
	  for (int i = 0; i < length; i++) {
		 if (searchstr.charAt(i) != 'h')continue;
		 count++;
		 searchstr.setCharAt(i, 'h');
	  }
	  System.out.println("Found " + count + " h's in the string.");
	  System.out.println(searchstr);
   }
}

上面的代码示例将产生以下结果。

Found 2 h's in the string.
hello how are you. 

标签(Label)

这个例子展示了当break或continue语句出现在循环中时,如何跳转到特定的标签。

public class NewClass {
   public static void main(String[] args) {
	  String strSearch = "This is the string in which you have to search for a substring.";
	  String substring = "substring";
	  boolean found = false;
	  int max = strSearch.length() - substring.length();
	  testlbl: for (int i = 0; i <= max; i++) {
		 int length = substring.length();
		 int j = i;
		 int k = 0;
		 while (length-- != 0) {
			if(strSearch.charAt(j++) != substring.charAt(k++)){
			   continue testlbl;
			}
		 }
		 found = true;
		 break testlbl;
	  }
	  if (found) {
		 System.out.println("Found the substring .");
	  } else {
		 System.out.println("did not find the substing in the string.");
	  }
   }
}

上面的代码示例将产生以下结果。

Found the substring .

enum 和 switch 语句使用

本示例显示如何使用Switch语句检查选择哪个枚举成员。

enum Car {
   lamborghini,tata,audi,fiat,honda
}
public class Main {
   public static void main(String args[]){
	  Car c;
	  c = Car.tata;
	  switch(c) {
		 case lamborghini:
			System.out.println("You choose lamborghini!");
			break;
		 case tata:
			System.out.println("You choose tata!");
			break;
		 case audi:
			System.out.println("You choose audi!");
			break;
		 case fiat:
			System.out.println("You choose fiat!");
			break;
		 case honda:
			System.out.println("You choose honda!");
			break;
		 default:
			System.out.println("I don't know your car.");
			break;
	  }
   }
}

上面的代码示例将产生以下结果。

You choose tata!

Enum(枚举)构造函数及方法的使用

本示例使用构造函数&getPrice()方法初始化枚举并显示枚举值。

enum Car {
   lamborghini(900),tata(2),audi(50),fiat(15),honda(12);
   private int price;
   Car(int p) {
	  price = p;
   }
   int getPrice() {
	  return price;
   } 
}
public class Main {
   public static void main(String args[]){
	  System.out.println("All car prices:");
	  for (Car c : Car.values()) System.out.println(
		 c + " costs " + c.getPrice() + " thousand dollars.");
   }
}

上面的代码示例将产生以下结果。

All car prices:
lamborghini costs 900 thousand dollars.
tata costs 2 thousand dollars.
audi costs 50 thousand dollars.
fiat costs 15 thousand dollars.
honda costs 12 thousand dollars.

for 和 foreach循环使用

这个例子使用for循环和foreach循环显示一个整型数组。

public class Main {
   public static void main(String[] args) {
	  int[] intary = { 1,2,3,4};
	  forDisplay(intary);
	  foreachDisplay(intary);
   }
   public static void forDisplay(int[] a) {  
	  System.out.println("Display an array using for loop");
	  for (int i = 0; i < a.length; i++) {
		 System.out.print(a[i] + " ");
	  }
	  System.out.println();
   }
   public static void foreachDisplay(int[] data) {
	  System.out.println("Display an array using for each loop");
	  for (int a  : data) {
		 System.out.print(a+ " ");
	  }
   }
}

上面的代码示例将产生以下结果。

Display an array using for loop
1 2 3 4 
Display an array using for each loop
1 2 3 4 

Varargs 可变参数使用

本示例创建sumvarargs()方法,它将int数的变量no作为参数,并返回这些参数的总和作为输出。

public class Main {
   static int  sumvarargs(int... intArrays) {
	  int sum, i;
	  sum = 0;
	  for(i = 0; i< intArrays.length; i++) {
		 sum += intArrays[i];
	  }
	  return(sum);
   }
   public static void main(String args[]) {
	  int sum = 0;
	  sum = sumvarargs(new int[]{10,12,33});
	  System.out.println("The sum of the numbers is: " + sum);
   }
}

上面的代码示例将产生以下结果。

The sum of the numbers is: 55

重载(overloading)方法中使用 Varargs

此示例显示如何将具有可变参数的方法作为输入进行重载。

public class Main {
   static void vaTest(int ... no) {
	  System.out.print(
		 "vaTest(int ...): " + "Number of args: " + no.length +" Contents: ");
	  for(int n : no)System.out.print(n + " ");
	  System.out.println();
   }
   static void vaTest(boolean ... bl) {
	  System.out.print(
		 "vaTest(boolean ...) " + "Number of args: " + bl.length + " Contents: ");
	  for(boolean b : bl)System.out.print(b + " ");
	  System.out.println();
   }
   static void vaTest(String msg, int ... no) {
	  System.out.print(
		 "vaTest(String, int ...): " + msg +"no. of arguments: "+ no.length +" Contents: ");
	  for(int  n : no)
	  System.out.print(n + " ");
	  System.out.println();
   }
   public static void main(String args[]) {
	  vaTest(1, 2, 3);
	  vaTest("Testing: ", 10, 20);
	  vaTest(true, false, false);
   }
}

上面的代码示例将产生以下结果。

vaTest(int ...): Number of args: 3 Contents: 1 2 3 
vaTest(String, int ...): Testing: no. of arguments: 2 
Contents: 10 20 
vaTest(boolean ...) Number of args: 3 Contents: 
true false false

打印图形

打印菱形

输出指定行数的菱形。

public class Diamond {
	public static void main(String[] args) {
		print(8); 
	}
 
	public static void print(int size) {
		if (size % 2 == 0) {
			size++; 
		}
		for (int i = 0; i < size / 2 + 1; i++) {
			for (int j = size / 2 + 1; j > i + 1; j--) {
				System.out.print(" "); 
			}
			for (int j = 0; j < 2 * i + 1; j++) {
				System.out.print("*"); 
			}
			System.out.println(); // 换行
		}
		for (int i = size / 2 + 1; i < size; i++) {
			for (int j = 0; j < i - size / 2; j++) {
				System.out.print(" "); 
			}
			for (int j = 0; j < 2 * size - 1 - 2 * i; j++) {
				System.out.print("*"); 
			}
			System.out.println(); 
		}
	}
}

输出结果

    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
	*

九九乘法表

输出九九乘法表。

public class MultiplicationTable {
	public static void main(String[] args) {
		for(int i=1;i<=9;i++) {
			for(int j=1;j<=i;j++) {
				System.out.print(j+"×"+i+"="+i*j+"\t");
			}
			System.out.println();
		}
	}
}

输出结果

1×1=1   
1×2=2   2×2=4   
1×3=3   2×3=6   3×3=9   
1×4=4   2×4=8   3×4=12  4×4=16  
1×5=5   2×5=10  3×5=15  4×5=20  5×5=25  
1×6=6   2×6=12  3×6=18  4×6=24  5×6=30  6×6=36  
1×7=7   2×7=14  3×7=21  4×7=28  5×7=35  6×7=42  7×7=49  
1×8=8   2×8=16  3×8=24  4×8=32  5×8=40  6×8=48  7×8=56  8×8=64  
1×9=9   2×9=18  3×9=27  4×9=36  5×9=45  6×9=54  7×9=63  8×9=72  9×9=81

打印倒立的三角形

打印倒立的三角形。

public class InvertedTriangle {
	public static void main(String[] args) {
		for (int m = 1; m <= 4; m++) {
			for (int n = 0; n <= m; n++) {
				System.out.print(" ");
			}
			for (int x = 1; x <= 7 -2 * (m - 1); x++) {
				System.out.print("*");
			}
			System.out.println();
		}        
	}
}

输出结果

  *******
   *****
	***
	 *

打印平行四边形

输出平行四边形。

public class Parallelogram {
	public static void main(String[] args) {
		for (int i = 1; i <=5; i++) {
			for (int j = 1; j <= 5 - i; j++) {
				System.out.print(" ");
			}
			for (int k = 1; k <= 5; k++) {
				System.out.print("*");
			}
			System.out.println();
		}
	}
}

输出结果

    *****
   *****
  *****
 *****
*****

打印矩形

输出矩形。

public class Rect {
	public static void main(String[] args) {
		for (int i = 1; i <= 5; i++) {
			System.out.print("*");
			for (int j = 1; j <= 5; j++) {
				System.out.print("*");
			}
			System.out.println();
		}
	}
}

输出结果

******
******
******
******
******

文件操作

文件路径比较

此示例显示如何使用File类的filename.compareTo(另一文件名)方法比较同一目录中两个文件的路径。

import java.io.File;

public class Main {
   public static void main(String[] args) {
	  File file1 = new File("C:/File/demo1.txt");
	  File file2 = new File("C:/java/demo1.txt");
	  
	  if(file1.compareTo(file2) == 0) {
		 System.out.println("Both paths are same!");
	  } else {
		 System.out.println("Paths are not same!");
	  }
   }
}

上面的代码示例将产生以下结果。

Paths are not same!

文件创建

此示例演示使用File类的File()构造函数和file.createNewFile()方法创建新文件的方式。

import java.io.File;
import java.io.IOException;

public class Main {
   public static void main(String[] args) {
	  try {
		 File file = new File("C:/myfile.txt");
		 
		 if(file.createNewFile())System.out.println("Success!");
		 else System.out.println ("Error, file already exists.");
	  }
	  catch(IOException ioe) {
		 ioe.printStackTrace();
	  }
   }
}

上面的代码示例将产生以下结果。

Success!

文件修改日期

此示例显示如何使用File类的file.lastModified()方法获取文件的最后修改日期。

import java.io.File;
import java.util.Date;

public class Main {
   public static void main(String[] args) {
	  File file = new File("Main.java");
	  Long lastModified = file.lastModified();
	  Date date = new Date(lastModified);
	  System.out.println(date);
   }
}

上面的代码示例将产生以下结果。

Tue 12 May 10:18:50 PDF 2009

指定目录创建文件

本示例演示如何使用File类的File.createTempFile()方法在指定的目录中创建文件。

import java.io.File;

public class Main {
   public static void main(String[] args) throws Exception {
	  File file = null;
	  File dir = new File("C:/");
	  file = File.createTempFile("JavaTemp", ".javatemp", dir);
	  System.out.println(file.getPath());
   }
}

上面的代码示例将产生以下结果。

C:\JavaTemp37056.javatemp

检测文件是否存在

此示例显示如何使用File类的file.exists()方法检查文件存在。

import java.io.File;

public class Main {
   public static void main(String[] args) {
	  File file = new File("C:/java.txt");
	  System.out.println(file.exists());
   }
}

上面的代码示例将产生以下结果。

true

设置文件只读

本示例演示如何使用File类的file.setReadOnly()和file.canWrite()方法使文件成为只读文件。

import java.io.File;

public class Main {
   public static void main(String[] args) {
	  File file = new File("C:/java.txt");
	  System.out.println(file.setReadOnly());
	  System.out.println(file.canWrite());
   }
}

上面的代码示例将产生以下结果。

true
false

文件重命名

本示例演示如何使用File类的oldName.renameTo(newName)方法重命名文件。

import java.io.File;

public class Main {
   public static void main(String[] args) {
	  File oldName = new File("C:/program.txt");
	  File newName = new File("C:/java.txt");
	  
	  if(oldName.renameTo(newName)) {
		 System.out.println("renamed");
	  } else {
		 System.out.println("Error");
	  }
   }
}

上面的代码示例将产生以下结果。

renamed

获取文件大小

此示例显示如何使用File类的file.exists()和file.length()方法以字节为单位获取文件的大小。

import java.io.File;

public class Main {
   public static long getFileSize(String filename) {
	  File file = new File(filename);
	  if (!file.exists() || !file.isFile()) {
		 System.out.println("File doesn\'t exist");
		 return -1;
	  }
	  return file.length();
   }
   public static void main(String[] args) {
	  long size = getFileSize("c:/java.txt");
	  System.out.println("Filesize in bytes: " + size);
   }
}

上面的代码示例将产生以下结果。

File size in bytes: 480

修改文件日期

此示例显示如何使用File类的fileToChange.lastModified()和fileToChange setLastModified()方法更改文件的上次修改时间。

import java.io.File;
import java.util.Date;

public class Main {
   public static void main(String[] args) throws Exception {
	  File fileToChange = new File ("C:/myjavafile.txt");
	  fileToChange.createNewFile();
	  Date filetime = new Date (fileToChange.lastModified());
	  System.out.println(filetime.toString());
	  System.out.println (fileToChange.setLastModified (System.currentTimeMillis()));
	  filetime = new Date (fileToChange.lastModified());
	  System.out.println(filetime.toString());
   }
}

上面的代码示例将产生以下结果。

Sat Oct 18 19:58:20 GMT+05:30 2008
true
Sat Oct 18 19:58:20 GMT+05:30 2008

创建临时文件

此示例显示如何使用File类的createTempFile()方法创建临时文件。

import java.io.*;

public class Main {
   public static void main(String[] args) throws Exception {
	  File temp = File.createTempFile ("pattern", ".suffix");
	  temp.deleteOnExit(); 
	  BufferedWriter out = new BufferedWriter (new FileWriter(temp));
	  out.write("aString");
	  System.out.println("temporary file created:");
	  out.close();
   }
}

上面的代码示例将产生以下结果。

temporary file created:

向文件增加内容

此示例显示如何使用filewriter方法在现有文件中附加字符串。

import java.io.*;

public class Main {
   public static void main(String[] args) throws Exception {
	  try {
		 BufferedWriter out = new BufferedWriter(new FileWriter("filename"));
		 out.write("aString1\n");
		 out.close();
		 out = new BufferedWriter(new FileWriter("filename",true));
		 out.write("aString2");
		 out.close();
		 BufferedReader in = new BufferedReader(new FileReader("filename"));
		 String str;
		 
		 while ((str = in.readLine()) != null) {
			System.out.println(str);
		 }
	  }
	  in.close();
	  catch (IOException e) {
		 System.out.println("exception occoured"+ e);
	  }
   }
}

上面的代码示例将产生以下结果。

aString1
aString2

将文件内容复制到另一个文件

以下实例演示了使用 BufferedWriter 类的 read 和 write 方法将文件内容复制到另一个文件

import java.io.*;
 
public class Main {
	public static void main(String[] args) throws Exception {
		BufferedWriter out1 = new BufferedWriter(new FileWriter("srcfile"));
		out1.write("string to be copied\n");
		out1.close();
		InputStream in = new FileInputStream(new File("srcfile"));
		OutputStream out = new FileOutputStream
		(new File("destnfile"));
		byte[] buf = new byte[1024];
		int len;
		while ((len = in.read(buf)) > 0) {
			out.write(buf, 0, len);
		}
		in.close();
		out.close();
		BufferedReader in1 = new BufferedReader(new FileReader("destnfile"));
		String str;
		while ((str = in1.readLine()) != null) {
			System.out.println(str);
		}
		in1.close();
	}
}

上面的代码示例将产生以下结果。

string to be copied

删除文件

此示例显示如何使用File类的delete()方法删除文件。

import java.io.*;

public class Main {
   public static void main(String[] args) { 
	  try {
		 BufferedWriter out = new BufferedWriter (new FileWriter("filename"));
		 out.write("aString1\n");
		 out.close();
		 boolean success = (new File("filename")).delete();
		 
		 if (success) {
			System.out.println("The file has been successfully deleted"); 
		 }
		 BufferedReader in = new BufferedReader(new FileReader("filename"));
		 String str;
		 
		 while ((str = in.readLine()) != null) {
			System.out.println(str);
		 }
		 in.close();
	  }catch (IOException e) {
		 System.out.println("exception occoured"+ e);
		 System.out.println("
			File does not exist or you are trying to read a file that has been deleted");
	  }
   }
}

上面的代码示例将产生以下结果。

The file has been successfully deleted
exception occouredjava.io.FileNotFoundException:
filename (The system cannot find the file specified)
File does not exist or you are trying to read a 
file that has been deleted

读文件

这个例子展示了如何使用BufferedReader类的readLine方法读取文件。

import java.io.*;

public class Main {
   public static void main(String[] args)  {
	  try {
		 BufferedReader in = new BufferedReader(new FileReader("c:\\filename"));
		 String str;
		 
		 while ((str = in.readLine()) != null) {
			System.out.println(str);
		 }
		 System.out.println(str);
	  } catch (IOException e) {
	  }
   }
}

上面的代码示例将产生以下结果。

aString

写文件

此示例显示如何使用BufferedWriter的写入方法写入文件。

import java.io.*;

public class Main {
   public static void main(String[] args) {
	  try {
		 BufferedWriter out = new BufferedWriter(new FileWriter("outfilename"));
		 out.write("aString");
		 out.close();
		 System.out.println("File created successfully");
	  }
	  catch (IOException e) {
	  }
   }
}

上面的代码示例将产生以下结果。

File created successfully.

目录操作

递归创建目录

以下示例显示了如何在File类的file.mkdirs()方法的帮助下递归地创建目录。

import java.io.File;
	
public class Main {
	public static void main(String[] args) {
		String directories = "D:\\a\\b\\c\\d\\e\\f\\g\\h\\i";
		File file = new File(directories);
		boolean result = file.mkdirs();
		System.out.println("Status = " + result);
	}
}

上面的代码示例将产生以下结果。

Status = true

删除目录

以下示例演示如何使用File类的dir.isDirectory(),dir.list()和deleteDir()方法删除目录后删除其目录。

import java.io.File;
	
public class Main {
	public static void main(String[] argv) throws Exception {
		deleteDir(new File("c:\\temp"));
	}
	public static boolean deleteDir(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir (new File(dir, children[i]));
		
				if (!success) {
					return false;
				}
			}
		}
		return dir.delete();
		System.out.println("The directory is deleted.");
	}
}

上面的代码示例将产生以下结果。

The directory is deleted.

判断目录是否为空

以下示例使用File类的file.isDirectory(),file.list()和file.getPath()方法获取目录的大小。

import java.io.File;
	
public class Main {
	public static void main(String[] args) {
		File file = new File("/data");
		if (file.isDirectory()) {
			String[] files = file.list();
			if (files.length > 0) {
				System.out.println("The " + file.getPath() + " is not empty!");
			}
		}
	}
}

上面的代码示例将产生以下结果。

The D://Java/file.txt is not empty!

判断文件是否隐藏

以下示例演示如何通过使用File类的file.isHidden()方法来获取文件隐藏的事实。

import java.io.File;
	
public class Main {
	public static void main(String[] args) {
		File file = new File("C:/Demo.txt");
		System.out.println(file.isHidden());
	}
}

上面的代码示例将产生以下结果。

True

打印目录结构

以下示例显示如何使用File类的file.getName()和file.listFiles()方法打印指定目录的层次结构。

import java.io.File;
import java.io.IOException;
	
public class FileUtil {
	public static void main(String[] a)throws IOException{
		showDir(1, new File("d:\\Java"));
	}
	static void showDir(int indent, File file) throws IOException {
		for (int i = 0; i 7lt; indent; i++) System.out.print('-');
		System.out.println(file.getName());
		if (file.isDirectory()) {
			File[] files = file.listFiles();
			for (int i = 0; i < files.length; i++) showDir(indent + 4, files[i]);
		}
	}
}

上面的代码示例将产生以下结果。

-Java
-----codes
---------string.txt
---------array.txt
-----tutorial

获取目录最后修改时间

以下示例演示了如何在File类的file.lastModified()方法的帮助下获取目录的最后修改时间。

import java.io.File;
import java.util.Date;
	
public class Main {
	public static void main(String[] args) {
		File file = new File("C://FileIO//demo.txt");
		System.out.println("last modifed:" + new Date(file.lastModified()));
	}
}

上面的代码示例将产生以下结果。

last modifed:10:20:54

获取上层目录

以下示例显示了如何使用File类的file.getParent()方法获取文件的父目录。

import java.io.File;
	
public class Main {
	public static void main(String[] args) {
		File file = new File("C:/File/demo.txt");
		String strParentDirectory = file.getParent();
		System.out.println("Parent directory is : " + strParentDirectory);
	}
}

上面的代码示例将产生以下结果。

Parent directory is : File

遍历目录中所有文件

以下示例演示了如何使用File类的dir.list()方法搜索并获取指定目录下所有文件的列表。

import java.io.File;
	
public class Main {
	public static void main(String[] argv) throws Exception {
		File dir = new File("directoryName");
		String[] children = dir.list();
	
		if (children == null) {
			System.out.println("does not exist or
				is not a directory");
		} else {
			for (int i = 0; i < children.length; i++) {
				String filename = children[i];
				System.out.println(filename);
			}
		}
	}
}

上面的代码示例将产生以下结果。

sdk
---vehicles
------body.txt
------color.txt
------engine.txt
---ships
------shipengine.txt

获取目录大小

以下示例显示如何借助FileUtils类的FileUtils.sizeofDirectory(File Name)方法获取目录的大小。

import java.io.File;
import org.apache.commons.io.FileUtils;
	
public class Main {
	public static void main(String[] args) {
		long size = FileUtils.sizeOfDirectory(new File("C:/Windows"));
		System.out.println("Size: " + size + " bytes");
	}
}

上面的代码示例将产生以下结果。

Size: 2048 bytes

遍历目录

以下示例演示如何在File类的dir.isDirectory()和dir.list()方法的帮助下遍历目录。

import java.io.File;
	
public class Main {
	public static void main(String[] argv) throws Exception {
		System.out.println("The Directory is traversed.");
		visitAllDirsAndFiles(C://Java);
	}
	public static void visitAllDirsAndFiles(File dir) {
		System.out.println(dir);
		if (dir.isDirectory()) {
			String[] children = dir.list();
	
			for (int i = 0; i < children.length; i++) {
				visitAllDirsAndFiles(new File(dir, children[i]));
			}
		}
	}
}

上面的代码示例将产生以下结果。

The Directory is traversed.

查看当前工作目录

以下示例显示如何使用getProperty()方法获取当前目录。

public class Main {
	public static void main(String[] args) {
		String curDir = System.getProperty("user.dir");
		System.out.println("You currently working in :" + curDir+ ": Directory");
	}
}

上面的代码示例将产生以下结果。

You currently working in :C:\Documents and Settings\user\
My Documents\NetBeansProjects\TestApp: Directory

遍历系统根目录

以下示例显示如何使用File类的listRoots()方法在系统中查找根目录。

import java.io.*;
	
public class Main {
	public static void main(String[] args) {
		File[] roots = File.listRoots();
		System.out.println("Root directories in your system are:");
	
		for (int i = 0; i < roots.length; i++) {
			System.out.println(roots[i].toString());
		}
	}
}

上面的代码示例将产生以下结果。

Root directories in your system are:
C:\
D:\
E:\
F:\
G:\
H:\

查找目录中文件

以下示例显示如何通过创建Filefiter来搜索目录中的特定文件。 以下示例显示文件名以'b'开头的所有文件。

import java.io.*;
	
public class Main {
	public static void main(String[] args) {
		File dir = new File("C:");
		FilenameFilter filter = new FilenameFilter() {
			public boolean accept (File dir, String name) {
				return name.startsWith("b");
			}
		};
		String[] children = dir.list(filter);
		if (children == null) {
			System.out.println("Either dir does not exist or is not a directory");
		} else {
			for (int i=0; i< children.length; i++) {
				String filename = children[i];
				System.out.println(filename);
			}
		}
	}
}

上面的代码示例将产生以下结果。

build
build.xml

打印目录中所有文件

以下示例显示如何使用File类的列表方法显示目录中包含的所有文件。

import java.io.*;
	
public class Main {
	public static void main(String[] args) {
		File dir = new File("C:");
		String[] children = dir.list();
	
		if (children == null) {
			System.out.println( "Either dir does not exist or is not a directory");
		} else {
			for (int i=0; i< children.length; i++) {
				String filename = children[i];
				System.out.println(filename);
			}
		}
	}
}

上面的代码示例将产生以下结果。

build
build.xml
destnfile
detnfile
filename
manifest.mf
nbproject
outfilename
src
srcfile
test

打印目录中所有目录

以下示例显示了如何显示包含在目录中的所有目录,并使用列出File类的方法的过滤器。

import java.io.*;
	
public class Main {
	public static void main(String[] args) {
		File dir = new File("F:");
		File[] files = dir.listFiles();
		FileFilter fileFilter = new FileFilter() {
			public boolean accept(File file) {
				return file.isDirectory();
			}
		};
		files = dir.listFiles(fileFilter);
		System.out.println(files.length);
	
		if (files.length == 0) {
			System.out.println("Either dir does not exist or is not a directory");
		} else {
			for (int i = 0; i< files.length; i++) {
				File filename = files[i];
				System.out.println(filename.toString());
			}
		}
	}
}

上面的代码示例将产生以下结果。

14
F:\C Drive Data Old HDD
F:\Desktop1
F:\harsh
F:\hharsh final
F:\hhhh
F:\mov
F:\msdownld.tmp
F:\New Folder
F:\ravi
F:\ravi3
F:\RECYCLER
F:\System Volume Information
F:\temp
F:\work

异常处理

异常处理方法

以下实例演示了使用 System 类的 System.err.println() 来展示异常的处理方法

class ExceptionDemo
{
	public static void main(String[] args) {
		try {
			throw new Exception("My Exception");
		} catch (Exception e) {
			System.err.println("Caught Exception");
			System.err.println("getMessage():" + e.getMessage());
			System.err.println("getLocalizedMessage():" + e.getLocalizedMessage());
			System.err.println("toString():" + e);
			System.err.println("printStackTrace():");
			e.printStackTrace();
		}
	}
}

以上代码运行输出结果为

Caught Exception
getMessage():My Exception
getLocalizedMessage():My Exception
toString():java.lang.Exception: My Exception
printStackTrace():
java.lang.Exception: My Exception
	at ExceptionDemo.main(ExceptionDemo.java:5)

多个异常处理

这个例子展示了如何处理多个异常,除以零?

public class Main {
	public static void main (String args[]) {
		int array[] = {20,20,40};
		int num1 = 15, num2 = 0;
		int result = 0;
		try {
			result = num1/num2;
			System.out.println("The result is" +result);
	
			for(int i = 2; i >=0; i--) {
				System.out.println("The value of array is" +array[i]);
			}
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("Error. Array is out of Bounds"+e);
		} catch (ArithmeticException e) {
			System.out.println ("Can't be divided by Zero"+e);
		}
	}
}

上面的代码示例将产生以下结果。

Can't be divided by Zerojava.lang.ArithmeticException: / by zero

Finally的用法

Java 中的 Finally 关键一般与try一起使用,在程序进入try块之后,无论程序是因为异常而中止或其它方式返回终止的,finally块的内容一定会被执行 。

public class ExceptionDemo2 {
	public static void main(String[] argv) {
		new ExceptionDemo2().doTheWork();
	}
	public void doTheWork() {
		Object o = null;
		for (int i = 0; i<5; i++) {
			try {
				o = makeObj(i);
			} catch (IllegalArgumentException e) {
				System.err.println("Error: ("+ e.getMessage()+").");
				return;
			} finally {
				System.err.println("All done");
				if (o==null)
					System.exit(0);
				}
				System.out.println(o);
			}
		}
	public Object makeObj(int type) throws IllegalArgumentException {
		if (type == 1)throw new IllegalArgumentException("Don't like type " + type);
			return new Object();
	}
}

上面的代码示例将产生以下结果。

All done
java.lang.Object@1b90b39
Error: (Don't like type 1).
All done

使用 catch 处理异常

以下实例演示了使用 catch 来处理异常的方法

public class Main{
	public static void main (String args[]) {
		int array[] = {20,20,40};
		int num1 = 15, num2 = 10;
		int result = 10;
		try {
			result = num1/num2;
			System.out.println("The result is" +result);
	
			for(int i = 5;i >=0; i--) {
				System.out.println("The value of array is" +array[i]);
			}
		} catch (Exception e) {
			System.out.println("Exception occoured : "+e);
		}
	}
}

上面的代码示例将产生以下结果。

The result is1
Exception occoured : java.lang.ArrayIndexOutOfBoundsException: 5

多线程异常处理

以下实例演示了多线程异常处理方法

class MyThread extends Thread{
	public void run(){
		System.out.println("Throwing in " +"MyThread");
		throw new RuntimeException();
	}
}
class Main {
	public static void main(String[] args){
		MyThread t = new MyThread();
		t.start();
		try{
			Thread.sleep(1000);
		}
		catch (Exception x){
			System.out.println("Caught it" + x);
		}
		System.out.println("Exiting main");
	}
}

以上代码运行输出结果为

Throwing in MyThread
Exception in thread "Thread-0" java.lang.RuntimeException
at testapp.MyThread.run(Main.java:19)
Exiting main

获取异常的堆栈信息

以下实例演示了使用异常类的 printStack() 方法来获取堆栈信息

public class Main{
	public static void main (String args[]){
		int array[]={20,20,40};
		int num1=15,num2=10;
		int result=10;
		try{
			result = num1/num2;
			System.out.println("The result is" +result);
			for(int i =5; i>=0; i--) {
				System.out.println("The value of array is" +array[i]);
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
}

以上代码运行输出结果为

The result is1
java.lang.ArrayIndexOutOfBoundsException: 5
	at testapp.Main.main(Main.java:28)

重载方法异常处理

以下实例演示了重载方法的异常处理

public class Main {
	double method(int i) throws Exception{
		return i/0;
	}
	boolean method(boolean b) {
		return !b;
	}
	static double method(int x, double y) throws Exception  {
		return x + y ;
	}
	static double method(double x, double y) {
		return x + y - 3;
	}
	public static void main(String[] args) {
		Main mn = new Main();
		try{
			System.out.println(method(10, 20.0));
			System.out.println(method(10.0, 20));
			System.out.println(method(10.0, 20.0));
			System.out.println(mn.method(10));
		}
		catch (Exception ex){
			System.out.println("exception occoure: "+ ex);
		}
	}
}

以上代码运行输出结果为

30.0
27.0
27.0
exception occoure: java.lang.ArithmeticException: / by zero

自定义异常

以下实例演示了通过继承 Exception 来实现自定义异常

class WrongInputException extends Exception {
	WrongInputException(String s) {
		super(s);
	}
}
class Input {
	void method() throws WrongInputException {
		throw new WrongInputException("Wrong input");
	}
}
class TestInput {
	public static void main(String[] args){
		try {
			new Input().method();
		}
		catch(WrongInputException wie) {
			System.out.println(wie.getMessage());
		}
	}
}

以上代码运行输出结果为

Wrong input

数据结构

数字求和运算

以下示例演示如何使用堆栈的概念添加前n个自然数。

import java.io.IOException;
	
public class AdditionStack {
	static int num;
	static int ans;
	static Stack theStack;
	public static void main(String[] args)
	
	throws IOException {
		num = 50;
		stackAddition();
		System.out.println("Sum=" + ans);
	}
	public static void stackAddition() {
		theStack = new Stack(10000);
		ans = 0;
		while (num > 0) {
			theStack.push(num);
			--num;
		}
		while (!theStack.isEmpty()) {
			int newN = theStack.pop();
			ans += newN;
		}
	}
}
class Stack {
	private int maxSize;
	private int[] data;
	private int top;
	public Stack(int s) {
		maxSize = s;
		data = new int[maxSize];
		top = -1;
	}
	public void push(int p) {
		data[++top] = p;
	}
	public int pop() {
		return data[top--];
	}
	public int peek() {
		return data[top];
	}
	public boolean isEmpty() {
		return (top == -1);
	}
}

上面的代码示例将产生以下结果。

The Sum Of 50is1275

链表头和尾

以下示例显示了如何在LinkedList类的linkedlistname.getFirst()和linkedlistname.getLast()的帮助下获取链表的第一个和最后一个元素。

import java.util.LinkedList;
	
public class Main {
	public static void main(String[] args) {
		LinkedList lList = new LinkedList();
		lList.add("100");
		lList.add("200");
		lList.add("300");
		lList.add("400");
		lList.add("500");
		System.out.println("First element of LinkedList is : " + lList.getFirst());
		System.out.println("Last element of LinkedList is : " + lList.getLast());
	}
}

上面的代码示例将产生以下结果。

First element of LinkedList is :100
Last element of LinkedList is :500

链表添加元素

以下示例显示了如何使用链接列表类的addFirst()和addLast()方法在链接列表的第一个和最后一个位置添加元素。

import java.util.LinkedList;
	
public class Main {
	public static void main(String[] args) {
		LinkedList lList = new LinkedList();
		lList.add("1");
		lList.add("2");
		lList.add("3");
		lList.add("4");
		lList.add("5");
		System.out.println(lList);
		
		lList.addFirst("0");
		System.out.println(lList);
		
		lList.addLast("6");
		System.out.println(lList);
	}
}

上面的代码示例将产生以下结果。

1, 2, 3, 4, 5
0, 1, 2, 3, 4, 5
0, 1, 2, 3, 4, 5, 6

利用堆栈将中缀表达式转换成后缀表达式

以下实例演示了如何使用堆栈进行表达式的堆栈将中缀(Infix)表达式转换成后缀(postfix)表达式

import java.io.IOException;
	
public class InToPost {
	private Stack theStack;
	private String input;
	private String output = "";
	public InToPost(String in) {
		input = in;
		int stackSize = input.length();
		theStack = new Stack(stackSize);
	}
	public String doTrans() {
		for (int j = 0; j < input.length(); j++) {
			char ch = input.charAt(j);
			switch (ch) {
				case '+':
				case '-':
					gotOper(ch, 1);
					break;
				case '*':
				case '/':
					gotOper(ch, 2);
					break;
				case '(':
					theStack.push(ch);
					break;
				case ')':
					gotParen(ch);
					break;
				default:
					output = output + ch;
					break;
			}
		}
		while (!theStack.isEmpty()) {
			output = output + theStack.pop();
		}
		System.out.println(output);
		return output;
	}
	public void gotOper(char opThis, int prec1) {
		while (!theStack.isEmpty()) {
			char opTop = theStack.pop();
			if (opTop == '(') {
				theStack.push(opTop);
				break;
			}
			else {
				int prec2;
				if (opTop == '+' || opTop == '-')
					prec2 = 1;
				else
					prec2 = 2;
				if (prec2 < prec1) {
					theStack.push(opTop);
					break;
				}
				else
					output = output + opTop;
				}
			}
			theStack.push(opThis);
		}
	public void gotParen(char ch){
		while (!theStack.isEmpty()) {
			char chx = theStack.pop();
			if (chx == '(')
				break;
			else
				output = output + chx;
		}
	}
	public static void main(String[] args)
		throws IOException {
			String input = "1+2*4/5-7+3/6";
			String output;
			InToPost theTrans = new InToPost(input);
			output = theTrans.doTrans();
			System.out.println("Postfix is " + output + '\n');
		}
	class Stack {
		private int maxSize;
		private char[] stackArray;
		private int top;
		public Stack(int max) {
			maxSize = max;
			stackArray = new char[maxSize];
			top = -1;
		}
		public void push(char j) {
			stackArray[++top] = j;
		}
		public char pop() {
			return stackArray[top--];
		}
		public char peek() {
			return stackArray[top];
		}
		public boolean isEmpty() {
			return (top == -1);
		}
	}
}

以上代码运行输出结果为

124*5/+7-36/+
Postfix is 124*5/+7-36/+

队列的实现

以下示例显示如何在employee structure中实施队列。

import java.util.LinkedList;
	
class GenQueue<E> {
	private LinkedList<E> list = new LinkedList<E>();
	public void enqueue(E item) {
		list.addLast(item);
	}
	public E dequeue() {
		return list.poll();
	}
	public boolean hasItems() {
		return !list.isEmpty();
	}
	public int size() {
		return list.size();
	}
	public void addItems(GenQueue<? extends E> q) {
		while (q.hasItems()) list.addLast(q.dequeue());
	}
}
public class GenQueueTest {
	public static void main(String[] args) {
		GenQueue<Employee> empList;
		empList = new GenQueue<Employee>();
		GenQueue<HourlyEmployee> hList;
	
		hList = new GenQueue<HourlyEmployee>();
		hList.enqueue(new HourlyEmployee("T", "D"));
		hList.enqueue(new HourlyEmployee("G", "B"));
		hList.enqueue(new HourlyEmployee("F", "S"));
		empList.addItems(hList);
		System.out.println("The employees' names are:");
	
		while (empList.hasItems()) {
			Employee emp = empList.dequeue();
			System.out.println(emp.firstName + " " + emp.lastName);
		}
	}
}
class Employee {
	public String lastName;
	public String firstName;
	public Employee() {
	}
	public Employee(String last, String first) {
		this.lastName = last;
		this.firstName = first;
	}
	public String toString() {
		return firstName + " " + lastName;
	}
}
class HourlyEmployee extends Employee {
	public double hourlyRate;
	public HourlyEmployee(String last, String first) {
		super(last, first);
	}
}

以上代码运行输出结果为

The employees' names are:
D T
B G
S F

栈的方法实现字符串反转

以下示例显示了如何在用户定义的方法StringReverserThroughStack()的帮助下使用堆栈反转字符串。

import java.io.IOException;
	
public class StringReverserThroughStack {
	private String input;
	private String output;
	public StringReverserThroughStack(String in) {
			input = in;
	}
	public String doRev() {
		int stackSize = input.length();
		Stack theStack = new Stack(stackSize);
	
		for (int i = 0; i < input.length(); i++) {
			char ch = input.charAt(i);
			theStack.push(ch);
		}
		output = "";
		while (!theStack.isEmpty()) {
			char ch = theStack.pop();
			output = output + ch;
		}
		return output;
	}
	public static void main(String[] args) throws IOException {
		String input = "Java Source and Support";
		String output;
		StringReverserThroughStack theReverser =
		new StringReverserThroughStack(input);
		output = theReverser.doRev();
		System.out.println("Reversed: " + output);
	}
	class Stack {
		private int maxSize;
		private char[] stackArray;
		private int top;
		
		public Stack(int max) {
			maxSize = max;
			stackArray = new char[maxSize];
			top = -1;
		}
		public void push(char j) {
			stackArray[++top] = j;
		}
		public char pop() {
			return stackArray[top--];
		}
		public char peek() {
			return stackArray[top];
		}
		public boolean isEmpty() {
			return (top == -1);
		}
	}
}

上面的代码示例将产生以下结果。

JavaStringReversal
Reversed:lasreveRgnirtSavaJ

链表元素查找

以下示例演示了如何使用linkedlistname.indexof(element)来搜索链接列表中的元素,以获取元素的第一个位置和linkedlistname.Lastindexof(elementname)以获取元素在链接列表中的最后位置。

import java.util.LinkedList;
	
public class Main {
	public static void main(String[] args) {
		LinkedList lList = new LinkedList();
		lList.add("1");
		lList.add("2");
		lList.add("3");
		lList.add("4");
		lList.add("5");
		lList.add("2");
		
		System.out.println("First index of 2 is:"+
		lList.indexOf("2"));
		
		System.out.println("Last index of 2 is:"+
		lList.lastIndexOf("2"));
	}
}

上面的代码示例将产生以下结果。

First index of 2 is: 1
Last index of 2 is: 5

实现堆栈

以下示例显示了如何通过创建用户输入元素的push()方法和用于从堆栈中检索元素的pop()方法来实现堆栈。

public class MyStack {
	private int maxSize;
	private long[] stackArray;
	private int top;
	
	public MyStack(int s) {
		maxSize = s;
		stackArray = new long[maxSize];
		top = -1;
	}
	public void push(long j) {
		stackArray[++top] = j;
	}
	public long pop() {
		return stackArray[top--];
	}
	public long peek() {
		return stackArray[top];
	}
	public boolean isEmpty() {
		return (top == -1);
	}
	public boolean isFull() {
		return (top == maxSize - 1);
	}
	public static void main(String[] args) {
		MyStack theStack = new MyStack(10);
		theStack.push(10);
		theStack.push(20);
		theStack.push(30);
		theStack.push(40);
		theStack.push(50);
	
		while (!theStack.isEmpty()) {
			long value = theStack.pop();
			System.out.print(value);
			System.out.print(" ");
		}
		System.out.println("");
	}
}

上面的代码示例将产生以下结果。

50 40 30 20 10

旋转向量

以下示例

import java.util.Collections;
import java.util.Vector;

public class Main {
public static void main(String[] args) {
	Vector v = new Vector();
	v.add("1");
	v.add("2");
	v.add("3");
	v.add("4");
	v.add("5");
	System.out.println(v);
	Collections.swap(v, 0, 4);
	System.out.println("After swapping");
	System.out.println(v);
	}
}

上面的代码示例将产生以下结果。

1 2 3 4 5
After swapping
5 2 3 4 1

更新链表元素

以下示例演示如何使用LinkedList类的listname.add()和listname.set()方法更新链接列表。

import java.util.LinkedList;

public class MainClass {
public static void main(String[] a) {
	LinkedList officers = new LinkedList();
	officers.add("B");
	officers.add("B");
	officers.add("T");
	officers.add("H");
	officers.add("P");
	System.out.println(officers);
	officers.set(2, "M");
	System.out.println(officers);
	}
}

上面的代码示例将产生以下结果。

[B, B, T, H, P]
[B, B, M, H, P]

获取向量的最大元素

以下实例演示了使用 Vector 类的 v.add() 方法及 Collection 类的 Collections.max() 来获取向量的最大元素

import java.util.Collections;
import java.util.Vector;
	
public class Main {
	public static void main(String[] args) {
		Vector v = new Vector();
		v.add(new Double("3.4324"));
		v.add(new Double("3.3532"));
		v.add(new Double("3.342"));
		v.add(new Double("3.349"));
		v.add(new Double("2.3"));
		Object obj = Collections.max(v);
		System.out.println("Maximum Element is : "+obj);
	}
}
Maximum Element is : 3.4324

向量的二分搜索

下面的示例演示如何在向量类的v.add()方法和Collection类的sort.Collection()方法的帮助下,对向量执行二分搜索。

import java.util.Collections;
import java.util.Vector;

public class Main {
public static void main(String[] args) {
	Vector v = new Vector();
	v.add("X");
	v.add("M");
	v.add("D");
	v.add("A");
	v.add("O");
	Collections.sort(v);
	System.out.println(v);
	int index = Collections.binarySearch(v, "D");
	System.out.println("Element found at : " + index);
	}
}

上面的代码示例将产生以下结果。

[A, D, M, O, X]
Element found at : 1

获取链表的元素

以下实例演示了使用 top() 和 pop() 方法来获取链表的元素

import java.util.*;
	
public class Main {
	private LinkedList list = new LinkedList();
	public void push(Object v) {
		list.addFirst(v);
	}
	public Object top() {
		return list.getFirst();
	}
	public Object pop() {
		return list.removeFirst();
	}
	public static void main(String[] args) {
		Main stack = new Main();
		for (int i = 30; i < 40; i++)
			stack.push(new Integer(i));
			System.out.println(stack.top());
			System.out.println(stack.pop());
			System.out.println(stack.pop());
			System.out.println(stack.pop());
	}
}

以上代码运行输出结果为

39
39
38
37

删除链表中的元素

以下实例演示了使用 clear() 方法来删除链表中的元素

import java.util.*;
	
public class Main {
	public static void main(String[] args) {
		LinkedList lList = new LinkedList();
		lList.add("1");
		lList.add("8");
		lList.add("6");
		lList.add("4");
		lList.add("5");
		System.out.println(lList);
		lList.subList(2, 4).clear();
		System.out.println(lList);
	}
}

以上代码运行输出结果为

[1, 8, 6, 4, 5]
[1, 8, 5]

集合

数组转集合

以下实例演示了使用 Java Util 类的 Arrays.asList(name) 方法将数组转换为集合

import java.util.*;
import java.io.*;
	
public class ArrayToCollection{
	public static void main(String args[]) throws IOException {
		BufferedReader in = new BufferedReader (new InputStreamReader(System.in));
		System.out.println("How many elements you want to add to the array: ");
		int n = Integer.parseInt(in.readLine());
		String[] name = new String[n];
	
		for(int i = 0; i < n; i++) {
			name[i] = in.readLine();
		}
		List<String> list = Arrays.asList(name);
		System.out.println();
	
		for(String li: list) {
			String str = li;
			System.out.print(str + " ");
		}
	}
}

以上代码运行输出结果为

How many elements you want to add to the array:
red white green

red white green

集合比较

以下实例将字符串转换为集合并使用 Collection 类的 Collection.min() 和 Collection.max() 来比较集合中的元素

import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;
	
public class MainClass {
	public static void main(String[] args) {
		String[] coins = { "Penny", "nickel", "dime", "Quarter", "dollar" };
		Set set = new TreeSet();
	
		for (int i = 0; i < coins.length; i++)set.add(coins[i]);
		System.out.println(Collections.min(set));
		System.out.println(Collections.min(set, String.CASE_INSENSITIVE_ORDER));
	
		for(int i=0; i<=10;i++)System.out.print('-');
		System.out.println(Collections.max(set));
		System.out.println(Collections.max(set,
		String.CASE_INSENSITIVE_ORDER));
	}
}

以上代码运行输出结果为

Penny
dime
-----------
nickel
Quarter

集合转数组

以下示例显示了如何使用Java Util类的list.add()和list.toArray()方法将集合转换为数组。

import java.util.*;
	
public class CollectionToArray{
	public static void main(String[] args){
		List<String> list = new ArrayList<String>();
		list.add("This ");
		list.add("is ");
		list.add("a ");
		list.add("good ");
		list.add("program.");
		String[] s1 = list.toArray(new String[0]);
	
		for(int i = 0; i< s1.length; ++i) {
			String contents = s1[i];
			System.out.print(contents);
		}
	}
}

上面的代码示例将产生以下结果。

This is a good program.

集合输出

下面的示例演示如何使用Java Util类的tMap.keySet(),tMap.values()和tMap.firstKey()方法打印集合。

import java.util.*;
	
public class TreeExample{
	public static void main(String[] args) {
		System.out.println("Tree Map Example!\n");
		TreeMap <Integer, String>tMap = new TreeMap<Integer, String>();
		tMap.put(1, "Sunday");
		tMap.put(2, "Monday");
		tMap.put(3, "Tuesday");
		tMap.put(4, "Wednesday");
		tMap.put(5, "Thursday");
		tMap.put(6, "Friday");
		tMap.put(7, "Saturday");
		System.out.println("Keys of tree map: " + tMap.keySet());
		System.out.println("Values of tree map: " + tMap.values());
		System.out.println("Key: 5 value: " + tMap.get(5)+ "\n");
		System.out.println(
			"First key: " + tMap.firstKey() + " Value: " + tMap.get(tMap.firstKey()) + "\n");
		System.out.println(
			"Last key: " + tMap.lastKey() + " Value: "+ tMap.get(tMap.lastKey()) + "\n");
		System.out.println("Removing first data: " + tMap.remove(tMap.firstKey()));
		System.out.println("Now the tree map Keys: " + tMap.keySet());
		System.out.println("Now the tree map contain: " + tMap.values() + "\n");
		System.out.println("Removing last data: " + tMap.remove(tMap.lastKey()));
		System.out.println("Now the tree map Keys: " + tMap.keySet());
		System.out.println("Now the tree map contain: " + tMap.values());
	}
}

以上代码运行输出结果为

C:\collection>javac TreeExample.java

C:\collection>java TreeExample
Tree Map Example!

Keys of tree map: [1, 2, 3, 4, 5, 6, 7]
Values of tree map: [Sunday, Monday, Tuesday, Wednesday,
Thursday, Friday, Saturday]
Key: 5 value: Thursday

First key: 1 Value: Sunday

Last key: 7 Value: Saturday

Removing first data: Sunday
Now the tree map Keys: [2, 3, 4, 5, 6, 7]
Now the tree map contain: [Monday, Tuesday, Wednesday,
Thursday, Friday, Saturday]

Removing last data: Saturday
Now the tree map Keys: [2, 3, 4, 5, 6]
Now the tree map contain: [Monday, Tuesday, Wednesday,
Thursday, Friday]

C:\collection>

只读集合

以下示例显示如何使用Collection类的Collections.unmodifiableList()方法使集合变为只读。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
	
public class Main {
	public static void main(String[] argv) throws Exception {
		List stuff = Arrays.asList(new String[] { "a", "b" });
		List list = new ArrayList(stuff);
		list = Collections.unmodifiableList(list);
		try {
			list.set(0, "new value");
		} catch (UnsupportedOperationException e) {
		}
		Set set = new HashSet(stuff);
		set = Collections.unmodifiableSet(set);
		Map map = new HashMap();
		map = Collections.unmodifiableMap(map);
		System.out.println("Collection is read-only now.");
	}
}

上面的代码示例将产生以下结果。

Collection is read-only now.

集合反转

以下示例演示如何在Collection和Listiterator类的listIterator()和Collection.reverse()方法的帮助下反转集合。

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
	
public class UtilDemo3 {
	public static void main(String[] args) {
		String[] coins = { "A", "B", "C", "D", "E" };
		List l = new ArrayList();
	
		for (int i = 0; i < coins.length; i++)l.add(coins[i]);
		ListIterator liter = l.listIterator();
		System.out.println("Before reversal");
		
		while (liter.hasNext())System.out.println(liter.next());
		Collections.reverse(l);
		liter = l.listIterator();
		System.out.println("After reversal");
		while (liter.hasNext())System.out.println(liter.next());
	}
}

上面的代码示例将产生以下结果。

Before reversal
A
B
C
D
E
After reversal
E
D
C
B
A

集合打乱顺序

以下实例演示了如何使用 Collections 类 Collections.shuffle() 方法来打乱集合元素的顺序

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
	
public class Main {
	public static void main(String[] argv) throws Exception {
		ArrayList<String> obj = new ArrayList<String>();
		obj.add("A");
		obj.add("E");
		obj.add("I");
		obj.add("O");
		obj.add("U");
		Collections.shuffle(obj);
		System.out.println(obj);
	}
}

以上代码运行输出结果为

[I, U, A, O, E]

集合大小

以下实例演示了如何使用 Collections 类 的collection.add() 来添加数据并使用 collection.size()来计算集合的长度

import java.util.*;
	
public class CollectionTest {
	public static void main(String [] args) {
		System.out.println( "Collection Example!\n" );
		int size;
		HashSet <String>collection = new HashSet <String>();
		String str1 = "Yellow", str2 = "White", str3 = "Green", str4 = "Blue";
		Iterator iterator;
		collection.add(str1);
		collection.add(str2);
		collection.add(str3);
		collection.add(str4);
		System.out.print("Collection data: ");
		iterator = collection.iterator();
	
		while (iterator.hasNext()){
			System.out.print(iterator.next() + " ");
		}
		System.out.println();
		size = collection.size();
	
		if (collection.isEmpty()){
			System.out.println("Collection is empty");
		} else {
			System.out.println( "Collection size: " + size);
		}
		System.out.println();
	}
}

以上代码运行输出结果为

Collection Example!
	
Collection data: Blue White Green Yellow
Collection size: 4

HashMap遍历

以下实例演示了如何使用 Collection 类的 iterator() 方法来遍历集合

import java.util.*;
	
public class Main {
	public static void main(String[] args) {
		HashMap< String, String> hMap = new HashMap< String, String>();
		hMap.put("1", "1st");
		hMap.put("2", "2nd");
		hMap.put("3", "3rd");
		Collection cl = hMap.values();
		Iterator itr = cl.iterator();
	
		while (itr.hasNext()) {
			System.out.println(itr.next());
		}
	}
}

以上代码运行输出结果为

1st
2nd
3rd

集合中添加不同类型元素

以下示例使用不同类型的集合类并在这些集合中添加一个元素。

import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;

public class Main {
	public static void main(String[] args) {
		List lnkLst = new LinkedList();
		lnkLst.add("element1");
		lnkLst.add("element2");
		lnkLst.add("element3");
		lnkLst.add("element4");
		displayAll(lnkLst);
	
		List aryLst = new ArrayList();
		aryLst.add("x");
		aryLst.add("y");
		aryLst.add("z");
		aryLst.add("w");
		displayAll(aryLst);
	
		Set hashSet = new HashSet();
		hashSet.add("set1");
		hashSet.add("set2");
		hashSet.add("set3");
		hashSet.add("set4");
		displayAll(hashSet);
	
		SortedSet treeSet = new TreeSet();
		treeSet.add("1");
		treeSet.add("2");
		treeSet.add("3");
		treeSet.add("4");
		displayAll(treeSet);
	
		LinkedHashSet lnkHashset = new LinkedHashSet();
		lnkHashset.add("one");
		lnkHashset.add("two");
		lnkHashset.add("three");
		lnkHashset.add("four");
		displayAll(lnkHashset);
	
		Map map1 = new HashMap();
		map1.put("key1", "J");
		map1.put("key2", "K");
		map1.put("key3", "L");
		map1.put("key4", "M");
		displayAll(map1.keySet());
		displayAll(map1.values());
	
		SortedMap map2 = new TreeMap();
		map2.put("key1", "JJ");
		map2.put("key2", "KK");
		map2.put("key3", "LL");
		map2.put("key4", "MM");
		displayAll(map2.keySet());
		displayAll(map2.values());
	
		LinkedHashMap map3 = new LinkedHashMap();
		map3.put("key1", "JJJ");
		map3.put("key2", "KKK");
		map3.put("key3", "LLL");
		map3.put("key4", "MMM");
		displayAll(map3.keySet());
		displayAll(map3.values());
	}
	static void displayAll(Collection col) {
		Iterator itr = col.iterator();
		while (itr.hasNext()) {
			String str = (String) itr.next();
			System.out.print(str + " ");
		}
		System.out.println();
	}
}

以上代码运行输出结果为

element1 element2 element3 element4
x y z w
set1 set2 set3 set4
1 2 3 4
one two three four
key4 key3 key2 key1
M L K J
key1 key2 key3 key4
JJ KK LL MM
key1 key2 key3 key4
JJJ KKK LLL MMM

使用 Enumeration 遍历 HashTable

以下实例演示了如何使用 Enumeration 类的 hasMoreElements 和 nextElement 方法来遍历输出 HashTable 中的内容

import java.util.Enumeration;
import java.util.Hashtable;
	
public class Main {
	public static void main(String[] args) {
		Hashtable ht = new Hashtable();
		ht.put("1", "One");
		ht.put("2", "Two");
		ht.put("3", "Three");
		Enumeration e = ht.elements();
		while(e.hasMoreElements()){
			System.out.println(e.nextElement());
		}
	}
}

以上代码运行输出结果为

Three
Two
One

遍历 HashTable 的键值

以下实例演示了如何使用 Hashtable 类的 keys() 方法来遍历输出键值

import java.util.Enumeration;
import java.util.Hashtable;
	
public class Main {
	public static void main(String[] args) {
		Hashtable ht = new Hashtable();
		ht.put("1", "One");
		ht.put("2", "Two");
		ht.put("3", "Three");
		Enumeration e = ht.keys();
		while (e.hasMoreElements()){
			System.out.println(e.nextElement());
		}
	}
}

以上代码运行输出结果为

3
2
1

查找 List 中的最大最小值

以下实例演示了如何使用 Collections 类的 max() 和 min() 方法来获取List中最大最小值

import java.util.*;
	
public class Main {
	public static void main(String[] args) {
		List list = Arrays.asList("one Two three Four five six one three Four".split(" "));
		System.out.println(list);
		System.out.println("max: " + Collections.max(list));
		System.out.println("min: " + Collections.min(list));
	}
}

以上代码运行输出结果为

[one, Two, three, Four, five, six, one, three, Four]
max: three
min: Four

List 截取

以下实例演示了如何使用 Collections 类的 indexOfSubList() 和 lastIndexOfSubList() 方法来查看子列表是否在列表中,并查看子列表在列表中所在的位置

import java.util.*;
	
public class Main {
	public static void main(String[] args) {
		List list = Arrays.asList("one Two three Four five six one three Four".split(" "));
		System.out.println("List :"+list);
	
		List sublist = Arrays.asList("three Four".split(" "));
		System.out.println("SubList :"+sublist);
		System.out.println(
			"indexOfSubList: " + Collections.indexOfSubList(list, sublist));
	
		System.out.println(
			"lastIndexOfSubList: " + Collections.lastIndexOfSubList(list, sublist));
	}
}

以上代码运行输出结果为

List :[one, Two, three, Four, five, six, one, three, Four]
SubList :[three, Four]
indexOfSubList: 2
lastIndexOfSubList: 7

List 元素替换

以下实例演示了如何使用 Collections 类的 replaceAll() 来替换List中所有的指定元素

import java.util.*;
	
public class Main {
	public static void main(String[] args) {
		List list = Arrays.asList("one Two three Four five six one three Four".split(" "));
		System.out.println("List :"+list);
		Collections.replaceAll(list, "one", "hundrea");
		System.out.println("replaceAll: " + list);
	}
}

以上代码运行输出结果为

List :[one, Two, three, Four, five, six, one, three, Four]
replaceAll: [hundrea, Two, three, Four, five, six, hundrea, three, Four]

List 循环移动元素

以下实例演示了如何使用 Collections 类的 rotate() 来循环移动元素,方法第二个参数指定了移动的起始位置

import java.util.*;
	
public class Main {
	public static void main(String[] args) {
		List list = Arrays.asList("one Two three Four five six".split(" "));
		System.out.println("List :"+list);
		Collections.rotate(list, 3);
		System.out.println("rotate: " + list);
	}
}

以上代码运行输出结果为

List :[one, Two, three, Four, five, six]
rotate: [Four, five, six, one, Two, three]

网络实例

获取指定主机的IP地址

以下示例显示了如何借助net.InetAddress类的InetAddress.getByName()方法将主机名更改为其特定IP地址。

import java.net.InetAddress;
import java.net.UnknownHostException;

public class GetIP {
   public static void main(String[] args) {
	  InetAddress address = null;
	  try {
		 address = InetAddress.getByName("www.google.com");
	  } catch (UnknownHostException e) {
		 System.exit(2);
	  }
	  System.out.println(address.getHostName() + "=" + address.getHostAddress());
	  System.exit(0);
   }
}

上面的代码示例将产生以下结果。

http://www.google.com = 173.194.202.147

连接到服务器

以下示例演示如何使用net.Socket类的sock.getInetAddress()方法与Web服务器建立连接。

import java.net.InetAddress;
import java.net.Socket;

public class WebPing {
   public static void main(String[] args) {
	  try {
		 InetAddress addr;
		 Socket sock = new Socket("www.google.com", 80);
		 addr = sock.getInetAddress();
		 System.out.println("Connected to " + addr);
		 sock.close();
	  } catch (java.io.IOException e) {
		 System.out.println("Can't connect to " + args[0]);
		 System.out.println(e);
	  }
   }
}

上面的代码示例将产生以下结果。

Connected to www.google.com/173.194.202.147

查看主机指定文件的最后修改时间

以下示例显示如何检查文件是否在服务器上修改。

import java.net.URL;
import java.net.URLConnection;

public class Main {
   public static void main(String[] argv)throws Exception {
	  URL u = new URL("http://127.0.0.1/java.bmp");
	  URLConnection uc = u.openConnection();
	  uc.setUseCaches(false);
	  long timestamp = uc.getLastModified();
	  System.out.println("The last modification time of java.bmp is :"+timestamp);
   }
}

上面的代码示例将产生以下结果。

The last modification time of java.bmp is :24 May 2009 12:14:50

多线程服务器

以下示例演示了如何使用Socket类的ssock.accept()方法和ServerSocket类的MultiThreadServer(套接字名称)方法创建多线程服务器。

import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MultiThreadServer implements Runnable {
   Socket csocket;
   MultiThreadServer(Socket csocket) {
	  this.csocket = csocket;
   }
   public static void main(String args[]) throws Exception { 
	  ServerSocket ssock = new ServerSocket(1234);
	  System.out.println("Listening");
	  
	  while (true) {
		 Socket sock = ssock.accept();
		 System.out.println("Connected");
		 new Thread(new MultiThreadServer(sock)).start();
	  }
   }
   public void run() {
	  try {
		 PrintStream pstream = new PrintStream(csocket.getOutputStream());
		 for (int i = 100; i >= 0; i--) {
			pstream.println(i + " bottles of beer on the wall");
		 }
		 pstream.close();
		 csocket.close();
	  } catch (IOException e) {
		 System.out.println(e);
	  }
   }
}

上面的代码示例将产生以下结果。

Listening
Connected

获取服务器文件大小

以下示例演示如何从服务器获取文件大小。

import java.net.URL;
import java.net.URLConnection;

public class Main {
   public static void main(String[] argv) throws Exception {
	  int size;
	  URL url = new URL("http://www.server.com");
	  URLConnection conn = url.openConnection();
	  size = conn.getContentLength();
	  
	  if (size < 0) System.out.println("Could not determine file size.");
	  else System.out.println("The size of file is = " + size + "bytes");
	  conn.getInputStream().close();
   }
}

上面的代码示例将产生以下结果。

The size of file is = 1312bytes

发送消息给客户端

以下示例演示了如何使用Socket类的ssock.accept()方法将套接字显示消息发送给单个客户端。

import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class BeerServer {
   public static void main(String args[]) throws Exception {
	  ServerSocket ssock = new ServerSocket(1234);
	  System.out.println("Listening");
	  Socket sock = ssock.accept();
	  ssock.close(); 
	  PrintStream ps = new PrintStream(sock.getOutputStream());
	  
	  for (int i = 10; i >= 0; i--) {
		 ps.println(i + " from Java Source and Support.");
	  }
	  ps.close();
	  sock.close();
   }
}

上面的代码示例将产生以下结果。

Listening
10 from Java Source and Support
9 from Java Source and Support
8 from Java Source and Support
7 from Java Source and Support
6 from Java Source and Support
5 from Java Source and Support
4 from Java Source and Support
3 from Java Source and Support
2 from Java Source and Support
1 from Java Source and Support
0 from Java Source and Support

连接到套接字

以下示例显示了如何通过使用ServerSocket类的server.accept()方法和Socket类的sock.getInetAddress()方法使服务器允许连接到套接字6123。

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketDemo {
   public static void main(String[] args) {
	  try {
		 ServerSocket server = new ServerSocket(6123);
		 while (true) {
			System.out.println("Listening");
			Socket sock = server.accept();
			InetAddress addr = sock.getInetAddress();
			System.out.println("Connection made to " + addr.getHostName() + " (
			   " + addr.getHostAddress() + ")");
			pause(5000);
			sock.close();
		 }
	  } catch (IOException e) {
		 System.out.println("Exception detected: " + e);
	  }
   }
   private static void pause(int ms) {
	  try {
		 Thread.sleep(ms);
	  }catch (InterruptedException e) {}
   }
}

上面的代码示例将产生以下结果。

Listening
Terminate batch job (Y/N)? n 
Connection made to 112.63.21.45

解析 URL

以下实例演示了如何使用 net.URL 类的 url.getProtocol() ,url.getFile() 等方法来解析 URL 地址

import java.net.URL;

public class Main {
   public static void main(String[] args) throws Exception {
	  URL url = new URL(args[0]);
	  System.out.println("URL is " + url.toString());
	  System.out.println("protocol is " + url.getProtocol());
	  System.out.println("file name is " + url.getFile());
	  System.out.println("host is " + url.getHost());
	  System.out.println("path is " + url.getPath());
	  System.out.println("port is " + url.getPort());
	  System.out.println("default port is " + url.getDefaultPort());
   }
}

上面的代码示例将产生以下结果。

URL is http://www.server.com
protocol is TCP/IP
file name is java_program.txt
host is 122.45.2.36
path is 
port is 2
default port is 1

获取 URL响应头的日期信息

以下实例演示了如何使用 HttpURLConnection 的 httpCon.getDate() 方法来获取 URL响应头的日期信息

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

public class Main{
   public static void main(String args[]) 
   throws Exception {
	  URL url = new URL("http://www.google.com");
	  HttpURLConnection httpCon = 
	  (HttpURLConnection) url.openConnection();
	  long date = httpCon.getDate();
	  if (date == 0)
	  System.out.println("No date information.");
	  else
	  System.out.println("Date: " + new Date(date));
   }
}

上面的代码示例将产生以下结果。

Date:05.26.2009

下载网页

以下示例显示如何读取和下载net.URL类的网页URL()构造函数。

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.net.URL;

public class Main {
   public static void main(String[] args) throws Exception {
	  URL url = new URL("http://www.google.com");
	  BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
	  BufferedWriter writer = new BufferedWriter(new FileWriter("data.html"));
	  String line;
	  
	  while ((line = reader.readLine()) != null) {
		 System.out.println(line);
		 writer.write(line);
		 writer.newLine();
	  }
	  reader.close();
	  writer.close();
   }
}

上面的代码示例将产生以下结果。

Welcome to Java Tutorial
	Here we have plenty of examples for you!
	
   Come and Explore Java!

通过ip查找主机名

以下示例显示了如何借助net.InetAddress类的InetAddress.getByName()方法将主机名更改为其特定IP地址。

import java.net.InetAddress;
import java.net.UnknownHostException;

public class NewClass1 {
   public static void main(String[] args) {
	  InetAddress ip;
	  String hostname;
	  try {
		 ip = InetAddress.getLocalHost();
		 hostname = ip.getHostName();
		 System.out.println("Your current IP address : " + ip);
		 System.out.println("Your current Hostname : " + hostname);
	  } catch (UnknownHostException e) {
		 e.printStackTrace();
	  }
   }
}

上面的代码示例将产生以下结果。

Your current IP address : localhost/127.0.0.1
Your current Hostname : localhost

查看端口是否已使用

以下实例演示了如何检测端口是否已经使用

import java.net.*;
import java.io.*;

public class Main {
   public static void main(String[] args) {
	  Socket Skt;
	  String host = "localhost";
	  
	  if (args.length > 0) {
		 host = args[0];
	  }
	  for (int i = 0; i < 1024; i++) {
		 try {
			System.out.println("Looking for "+ i);
			Skt = new Socket(host, i);
			System.out.println("There is a server on port " + i + " of " + host);
		 } catch (UnknownHostException e) {
			System.out.println("Exception occured"+ e);
			break;
		 } catch (IOException e) {}
	  }
   }
}

上面的代码示例将产生以下结果。

Looking for 0
Looking for 1
Looking for 2
Looking for 3
Looking for 4. . . 

查找代理设置

以下示例显示如何使用systemSetting的put方法和HttpURLConnection类的getResponse方法在系统上查找代理设置并创建代理连接。

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.URI;

public class Main{
   public static void main(String s[]) throws Exception {
	  try {
		 Properties systemSettings = System.getProperties();
		 systemSettings.put("proxySet", "true");
		 systemSettings.put("http.proxyHost", "proxy.mycompany1.local");
		 systemSettings.put("http.proxyPort", "80");
		 
		 URL u = new URL("http://www.google.com");
		 HttpURLConnection con = (HttpURLConnection)u.openConnection();
		 System.out.println(con.getResponseCode() + " : " + con.getResponseMessage());
		 System.out.println(con.getResponseCode() == HttpURLConnection.HTTP_OK);
	  } catch (Exception e) {
		 e.printStackTrace();
		 System.out.println(false);
	  }
	  System.setProperty("java.net.useSystemProxies", "true");
	  Proxy proxy = (Proxy) ProxySelector.getDefault().select(new URI(
		 "http://www.yahoo.com/")).iterator().
	  next();;
	  System.out.println("proxy hostname : " + proxy.type());
	  InetSocketAddress addr = (InetSocketAddress)proxy.address();
	  
	  if (addr == null) {
		 System.out.println("No Proxy");
	  } else {
		 System.out.println("proxy hostname : " + addr.getHostName());
		 System.out.println("proxy port : " + addr.getPort());
	  }
   }
}

上面的代码示例将产生以下结果。

200 : OK
true
proxy hostname : HTTP
proxy hostname : proxy.mycompany1.local
proxy port : 80

创建套接字

以下示例演示如何演唱Socket类的Socket构造函数。并且还使用getLocalPort()getLocalAddress,getInetAddress()和getPort()方法获取Socket细节。

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

public class Main {
   public static void main(String[] args) {
	  try {
		 InetAddress addr = InetAddress.getByName("74.125.67.100");
		 Socket theSocket = new Socket(addr, 80);
		 System.out.println("Connected to " 
			+ theSocket.getInetAddress()
			+ " on port " + theSocket.getPort() + " from port "
			+ theSocket.getLocalPort() + " of " 
			+ theSocket.getLocalAddress());
	  } catch (UnknownHostException e) {
		 System.err.println("I can't find " + e  );
	  } catch (SocketException e) {
		 System.err.println("Could not connect to " +e );
	  } catch (IOException e) {
		 System.err.println(e);
	  }
   }
}

上面的代码示例将产生以下结果。

Connected to /74.125.67.100 on port 80 from port 
2857 of /192.168.1.4

线程

查看线程是否存活

以下实例演示了如何通过继承 Thread 类并使用 isAlive() 方法来检测一个线程是否存活

public class TwoThreadAlive extends Thread {
   public void run() {
	  for (int i = 0; i < 10; i++) {
		 printMsg();
	  }
   }
 
   public void printMsg() {
	  Thread t = Thread.currentThread();
	  String name = t.getName();
	  System.out.println("name=" + name);
   }
 
   public static void main(String[] args) {
	  TwoThreadAlive tt = new TwoThreadAlive();
	  tt.setName("Thread");
	  System.out.println("before start(), tt.isAlive()=" + tt.isAlive());
	  tt.start();
	  System.out.println("just after start(), tt.isAlive()=" + tt.isAlive());
	  for (int i = 0; i < 10; i++) {
		 tt.printMsg();
	  }
	  System.out.println("The end of main(), tt.isAlive()=" + tt.isAlive());
   }
}

以上代码运行输出结果为

before start(), tt.isAlive()=false
just after start(), tt.isAlive()=true
name=main
name=Thread
name=main
name=main
name=main
name=main
name=main
name=main
name=main
name=main
name=main
name=Thread
name=Thread
name=Thread
name=Thread
name=Thread
The end of main(), tt.isAlive()=true
name=Thread
name=Thread
name=Thread
name=Thread

获取当前线程名称

以下实例演示了如何通过继承 Thread 类并使用 getName() 方法来获取当前线程名称

public class TwoThreadGetName extends Thread {
   public void run() {
	  for (int i = 0; i < 10; i++) {
		 printMsg();
	  }
   }
   public void printMsg() {
	  Thread t = Thread.currentThread();
	  String name = t.getName();
	  System.out.println("name=" + name);
   } 
   public static void main(String[] args) {
	  TwoThreadGetName tt = new TwoThreadGetName();
	  tt.start();
	  for (int i = 0; i < 10; i++) {
		 tt.printMsg();
	  }
   }
}

以上代码运行输出结果为

name=main
name=main
name=main
name=main
name=main
name=Thread-0
name=Thread-0
name=Thread-0
name=Thread-0
name=Thread-0
name=main
name=Thread-0
name=main
name=Thread-0
name=main
name=Thread-0
name=main
name=Thread-0
name=main
name=Thread-0

状态监测

以下实例演示了如何通过继承 Thread 类并使用 currentThread.getName() 方法来监测线程的状态

class MyThread extends Thread{
   boolean waiting= true;
   boolean ready= false;
   MyThread() {
   }
   public void run() {
	  String thrdName = Thread.currentThread().getName();
	  System.out.println(thrdName + " starting.");
	  while(waiting) 
	  System.out.println("waiting:"+waiting); 
	  System.out.println("waiting...");
	  startWait(); 
	  try {
		 Thread.sleep(1000);
	  }
	  catch(Exception exc) {
		 System.out.println(thrdName + " interrupted.");
	  }
	  System.out.println(thrdName + " terminating.");
   }
   synchronized void startWait() {
	  try {
		 while(!ready) wait();
	  }
	  catch(InterruptedException exc) {
		 System.out.println("wait() interrupted");
	  }
   }
   synchronized void notice() {
	  ready = true;
	  notify();
   }
}
public class Main {
   public static void main(String args[]) 
   throws Exception{
	  MyThread thrd = new MyThread();
	  thrd.setName("MyThread #1");
	  showThreadStatus(thrd);
	  thrd.start();
	  Thread.sleep(50);
	  showThreadStatus(thrd);
	  thrd.waiting = false;
	  Thread.sleep(50); 
	  showThreadStatus(thrd);
	  thrd.notice();
	  Thread.sleep(50);
	  showThreadStatus(thrd);
	  while(thrd.isAlive()) 
	  System.out.println("alive");
	  showThreadStatus(thrd);
   }
   static void showThreadStatus(Thread thrd) {
	  System.out.println(thrd.getName() + "Alive:=" + thrd.isAlive() + " State:=" + thrd.getState());
   }
}

以上代码运行输出结果为

……
alive
alive
MyThread #1 terminating.
alive
……

线程优先级设置

以下实例演示了如何通过setPriority() 方法来设置线程的优先级

public class SimplePriorities extends Thread {
   private int countDown = 5;
   private volatile double d = 0; 
   public SimplePriorities(int priority) {
	  setPriority(priority);
	  start();
   }
   public String toString() {
	  return super.toString() + ": " + countDown;
   }
   public void run() {
	  while(true) {
		 for(int i = 1; i < 100000; i++)
		 d = d + (Math.PI + Math.E) / (double)i;
		 System.out.println(this);
		 if(--countDown == 0) return;
	  }
   }
   public static void main(String[] args) {
	  new SimplePriorities(Thread.MAX_PRIORITY);
	  for(int i = 0; i < 5; i++)
	  new SimplePriorities(Thread.MIN_PRIORITY);
   }
}

以上代码运行输出结果为

Thread[Thread-1,1,main]: 5
Thread[Thread-2,1,main]: 5
Thread[Thread-3,1,main]: 5
Thread[Thread-0,10,main]: 5
Thread[Thread-3,1,main]: 4
Thread[Thread-0,10,main]: 4
Thread[Thread-1,1,main]: 4
Thread[Thread-5,1,main]: 5
Thread[Thread-4,1,main]: 5
Thread[Thread-2,1,main]: 4
Thread[Thread-0,10,main]: 3
Thread[Thread-1,1,main]: 3
Thread[Thread-4,1,main]: 4
Thread[Thread-2,1,main]: 3
……

解决死锁

以下示例演示了如何使用线程的概念来解决死锁问题。

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;

public class DeadlockDetectingLock extends ReentrantLock {
   private static List deadlockLocksRegistry = new ArrayList();
   private static synchronized void registerLock(DeadlockDetectingLock ddl) {
	  if (!deadlockLocksRegistry.contains(ddl)) deadlockLocksRegistry.add(ddl);
   }
   private static synchronized void unregisterLock(DeadlockDetectingLock ddl) {
	  if (deadlockLocksRegistry.contains(ddl)) deadlockLocksRegistry.remove(ddl);
   }
   private List hardwaitingThreads = new ArrayList();
   private static synchronized void markAsHardwait(List l, Thread t) {
	  if (!l.contains(t)) l.add(t);
   }
   private static synchronized void freeIfHardwait(List l, Thread t) {
	  if (l.contains(t)) l.remove(t);
   }
   private static Iterator getAllLocksOwned(Thread t) {
	  DeadlockDetectingLock current;
	  ArrayList results = new ArrayList();
	  Iterator itr = deadlockLocksRegistry.iterator();
   
	  while (itr.hasNext()) {
		 current = (DeadlockDetectingLock) itr.next();
		 if (current.getOwner() == t)results.add(current);
	  } 
	  return results.iterator();
   } 
   private static Iterator getAllThreadsHardwaiting(DeadlockDetectingLock l) {
	  return l.hardwaitingThreads.iterator();
   } 
   private static synchronized boolean canThreadWaitOnLock (
	  Thread t,DeadlockDetectingLock l) {
	  
	  Iterator locksOwned = getAllLocksOwned(t);
	  while (locksOwned.hasNext()) {
		 DeadlockDetectingLock current = (DeadlockDetectingLock) locksOwned.next();
		 if (current == l)return false;
		 Iterator waitingThreads = getAllThreadsHardwaiting(current);
	  
		 while (waitingThreads.hasNext()) {
			Thread otherthread = (Thread) waitingThreads.next();
			if (!canThreadWaitOnLock(otherthread, l)) {
			   return false;
			}
		 }
	  }
	  return true;
   } 
   public DeadlockDetectingLock() {
	  this(false, false);
   } 
   public DeadlockDetectingLock(boolean fair) {
	  this(fair, false);
   } 
   private boolean debugging;
   public DeadlockDetectingLock(boolean fair, boolean debug) {
	  super(fair);
	  debugging = debug;
	  registerLock(this);
   } 
   public void lock() {
	  if (isHeldByCurrentThread()) {
		 if (debugging)
		 System.out.println("Already Own Lock");
		 super.lock();
		 freeIfHardwait(hardwaitingThreads, 
		 Thread.currentThread());
		 return;
	  } 
	  markAsHardwait(hardwaitingThreads, Thread.currentThread());
	  if (canThreadWaitOnLock(Thread.currentThread(), this)) {
		 if (debugging) System.out.println("Waiting For Lock");
		 super.lock();
		 freeIfHardwait(hardwaitingThreads, Thread.currentThread()); 
		 
		 if (debugging)System.out.println("Got New Lock");
	  } else {
		 throw new DeadlockDetectedException("DEADLOCK");
	  }
   }
   public void lockInterruptibly() throws InterruptedException {
	  lock();
   }
   public class DeadlockDetectingCondition implements Condition {
	  Condition embedded;
	  protected DeadlockDetectingCondition(ReentrantLock lock, Condition embedded) {
		 this.embedded = embedded;
	  } 
	  public void await() throws InterruptedException {
		 try {
			markAsHardwait(hardwaitingThreads, Thread.currentThread());
			embedded.await();
		 }
		 finally {
			freeIfHardwait(hardwaitingThreads, 
			Thread.currentThread());
		 }
	  } 
	  public void awaitUninterruptibly() {
		 markAsHardwait(hardwaitingThreads, Thread.currentThread());
		 embedded.awaitUninterruptibly();
		 freeIfHardwait(hardwaitingThreads, Thread.currentThread());
	  } 
	  public long awaitNanos(long nanosTimeout) throws InterruptedException {
		 try {
			markAsHardwait(hardwaitingThreads, 
			Thread.currentThread());
			return embedded.awaitNanos(nanosTimeout);
		 }
		 finally {
			freeIfHardwait(hardwaitingThreads, 
			Thread.currentThread());
		 }
	  } 
	  public boolean await(long time, TimeUnit unit) throws InterruptedException {
		 try {
			markAsHardwait(hardwaitingThreads, Thread.currentThread());
			return embedded.await(time, unit);
		 } 
		 finally {
			freeIfHardwait(hardwaitingThreads, Thread.currentThread());
		 } 
	  }
	  public boolean awaitUntil(Date deadline) throws InterruptedException {
		 try {
			markAsHardwait(hardwaitingThreads, Thread.currentThread());
			return embedded.awaitUntil(deadline);
		 } 
		 finally {
			freeIfHardwait(hardwaitingThreads, Thread.currentThread());
		 }
	  } 
	  public void signal() {
		 embedded.signal();
	  } 
	  public void signalAll() {
		 embedded.signalAll();
	  }
   }
   public Condition newCondition() {
	  return new DeadlockDetectingCondition(this, super.newCondition());
   }
   private static Lock a = new DeadlockDetectingLock(false, true);
   private static Lock b = new DeadlockDetectingLock(false, true);
   private static Lock c = new DeadlockDetectingLock(false, true);
   
   private static Condition wa = a.newCondition();
   private static Condition wb = b.newCondition();
   private static Condition wc = c.newCondition();
   private static void delaySeconds(int seconds) {
	  try {
		 Thread.sleep(seconds * 1000);
	  } catch (InterruptedException ex) {}
   }
   private static void awaitSeconds(Condition c, int seconds) {
	  try {
		 c.await(seconds, TimeUnit.SECONDS);
	  } catch (InterruptedException ex) {}
   }
   private static void testOne() {
	  new Thread(new Runnable() {
		 public void run() {
			System.out.println("thread one grab a");
			a.lock();
			delaySeconds(2);
			System.out.println("thread one grab b");
			b.lock();
			delaySeconds(2);
			a.unlock();
			b.unlock();
		 }
	  }).start();
	  new Thread(new Runnable() {
		 public void run() {
			System.out.println("thread two grab b");
			b.lock();
			delaySeconds(2);
			System.out.println("thread two grab a");
			a.lock();
			delaySeconds(2);
			a.unlock();
			b.unlock();
		 }
	  }).start();
   }
   private static void testTwo() {
	  new Thread(new Runnable() {
		 public void run() {
			System.out.println("thread one grab a");
			a.lock();
			delaySeconds(2) ;
			System.out.println("thread one grab b");
			b.lock();
			delaySeconds(10); 
			a.unlock();
			b.unlock();
		 }
	  }).start();
	  new Thread(new Runnable() {
		 public void run() {
			System.out.println("thread two grab b");
			b.lock();
			delaySeconds(2);
			System.out.println("thread two grab c");
			c.lock();
			delaySeconds(10);
			b.unlock();
			c.unlock();
		 }
	  }).start();
	  new Thread(new Runnable() {
		 public void run() {
			System.out.println("thread three grab c");
			c.lock();
			delaySeconds(4);
			System.out.println("thread three grab a");
			a.lock();
			delaySeconds(10);
			c.unlock();
			a.unlock();
		 }
	  }).start();
   }
   private static void testThree() {
	  new Thread(new Runnable() {
		 public void run() {
			System.out.println("thread one grab b");
			b.lock();
			System.out.println("thread one grab a");
			a.lock();
			delaySeconds(2);
			System.out.println("thread one waits on b");
			awaitSeconds(wb, 10);
			a.unlock();
			b.unlock();
		 }
	  }).start();
	  new Thread(new Runnable() {
		 public void run() {
			delaySeconds(1);
			System.out.println("thread two grab b");
			b.lock();
			System.out.println("thread two grab a");
			a.lock();
			delaySeconds(10);
			b.unlock();
			c.unlock();
		 }
	  }).start();
   }
   public static void main(String args[]) {
	  int test = 1;
	  if (args.length > 0) test = Integer.parseInt(args[0]);
	  switch (test) {
		 case 1:
			testOne();
			break;
		 case 2:
			testTwo(); 
			break; 
		 case 3:
			testThree();
			break;
		 default:
			System.err.println("usage: java DeadlockDetectingLock [ test# ]");
	  }
	  delaySeconds(60);
	  System.out.println("--- End Program ---");
	  System.exit(0);
   }
}
class DeadlockDetectedException extends RuntimeException {
   public DeadlockDetectedException(String s) {
	  super(s);
   }
}

上面的代码示例将产生以下结果。

thread one grab a
Waiting For Lock
Got New Lock
thread two grab b
Waiting For Lock
Got New Lock
thread one grab b
Waiting For Lock
thread two grab a
Exception in thread "Thread-1" 
DeadlockDetectedException:DEADLOCK
   at DeadlockDetectingLock.
	  lock(DealockDetectingLock.java:152)
   at java.lang.Thread.run(Thread.java:595)

获取线程id

以下实例演示了如何使用 getThreadId() 方法获取线程id

public class Main extends Object implements Runnable {
  private ThreadID var;
 
  public Main(ThreadID v) {
	this.var = v;
  }
 
  public void run() {
	try {
	  print("var getThreadID =" + var.getThreadID());
	  Thread.sleep(2000);
	  print("var getThreadID =" + var.getThreadID());
	} catch (InterruptedException x) {
	}
  }
 
  private static void print(String msg) {
	String name = Thread.currentThread().getName();
	System.out.println(name + ": " + msg);
  }
 
  public static void main(String[] args) {
	ThreadID tid = new ThreadID();
	Main shared = new Main(tid);
 
	try {
	  Thread threadA = new Thread(shared, "threadA");
	  threadA.start();
 
	  Thread.sleep(500);
 
	  Thread threadB = new Thread(shared, "threadB");
	  threadB.start();
 
	  Thread.sleep(500);
 
	  Thread threadC = new Thread(shared, "threadC");
	  threadC.start();
	} catch (InterruptedException x) {
	}
  }
}
 
class ThreadID extends ThreadLocal {
  private int nextID;
 
  public ThreadID() {
	nextID = 10001;
  }
 
  private synchronized Integer getNewID() {
	Integer id = new Integer(nextID);
	nextID++;
	return id;
  }
 
 
  protected Object initialValue() {
	print("in initialValue()");
	return getNewID();
  }
 
  public int getThreadID() {
	Integer id = (Integer) get();
	return id.intValue();
  }
 
  private static void print(String msg) {
	String name = Thread.currentThread().getName();
	System.out.println(name + ": " + msg);
  }
}

以上代码运行输出结果为

threadA: in initialValue()
threadA: var getThreadID =10001
threadB: in initialValue()
threadB: var getThreadID =10002
threadC: in initialValue()
threadC: var getThreadID =10003
threadA: var getThreadID =10001
threadB: var getThreadID =10002
threadC: var getThreadID =10003

线程挂起

以下实例演示了如何将线程挂起

public class SleepingThread extends Thread {
   private int countDown = 5;
   private static int threadCount = 0;
   
   public SleepingThread() {
	  super("" + ++threadCount);
	  start();
   }
   public String toString() { 
	  return "#" + getName() + ": " + countDown;
   }
   public void run() {
	  while (true) {
		 System.out.println(this);
		 if (--countDown == 0) return;
		 try {
			sleep(100);
		 } catch (InterruptedException e) {
			throw new RuntimeException(e);
		 }
	  }
   }
   public static void main(String[] args) throws InterruptedException {
	  for (int i = 0; i < 5; i++) new SleepingThread().join();
	  System.out.println("The thread has been suspened.");
   }
}

以上代码运行输出结果为

#1: 5
#1: 4
#1: 3
#1: 2
#1: 1
#2: 5
#2: 4
#2: 3
#2: 2
#2: 1
#3: 5
#3: 4
#3: 3
#3: 2
#3: 1
#4: 5
#4: 4
#4: 3
#4: 2
#4: 1
#5: 5
#5: 4
#5: 3
#5: 2
#5: 1
The thread has been suspened.

停止线程

以下示例演示了如何通过在Timer类的方法的帮助下创建用户定义的方法run()来停止线程。

import java.util.Timer;
import java.util.TimerTask;

class CanStop extends Thread {
   private volatile boolean stop = false;
   private int counter = 0;
   
   public void run() {
	  while (!stop && counter < 10000) {
		 System.out.println(counter++);
	  }
	  if (stop)
	  System.out.println("Detected stop"); 
   }
   public void requestStop() {
	  stop = true;
   }
}
public class Stopping {
   public static void main(String[] args) {
	  final CanStop stoppable = new CanStop();
	  stoppable.start();
	  
	  new Timer(true).schedule(new TimerTask() {
		 public void run() {
			System.out.println("Requesting stop");
			stoppable.requestStop();
		 }
	  }, 
	  350);
   }
} 

以上代码运行输出结果为

Detected stop

生产者消费者问题

以下示例演示了如何使用线程解决生产者消费者问题。

public class ProducerConsumerTest {
   public static void main(String[] args) {
	  CubbyHole c = new CubbyHole();
	  Producer p1 = new Producer(c, 1);
	  Consumer c1 = new Consumer(c, 1);
	  p1.start(); 
	  c1.start();
   }
}
class CubbyHole {
   private int contents;
   private boolean available = false;
   
   public synchronized int get() {
	  while (available == false) {
		 try {
			wait();
		 } catch (InterruptedException e) {}
	  }
	  available = false;
	  notifyAll();
	  return contents;
   }
   public synchronized void put(int value) {
	  while (available == true) {
		 try {
			wait();
		 } catch (InterruptedException e) { } 
	  }
	  contents = value;
	  available = true;
	  notifyAll();
   }
}
class Consumer extends Thread {
   private CubbyHole cubbyhole;
   private int number;
   
   public Consumer(CubbyHole c, int number) {
	  cubbyhole = c;
	  this.number = number;
   }
   public void run() {
	  int value = 0;
	  for (int i = 0; i < 10; i++) {
		 value = cubbyhole.get();
		 System.out.println("Consumer #" + this.number + " got: " + value);
	  }
   }
}
class Producer extends Thread {
   private CubbyHole cubbyhole;
   private int number;
   public Producer(CubbyHole c, int number) {
	  cubbyhole = c;
	  this.number = number;
   } 
   public void run() {
	  for (int i = 0; i < 10; i++) {
		 cubbyhole.put(i);
		 System.out.println("Producer #" + this.number + " put: " + i);
		 try {
			sleep((int)(Math.random() * 100));
		 } catch (InterruptedException e) { }
	  } 
   }
} 

以上代码运行输出结果为

Producer #1 put: 0
Consumer #1 got: 0
Producer #1 put: 1
Consumer #1 got: 1
Producer #1 put: 2
Consumer #1 got: 2
Producer #1 put: 3
Consumer #1 got: 3
Producer #1 put: 4
Consumer #1 got: 4
Producer #1 put: 5
Consumer #1 got: 5
Producer #1 put: 6
Consumer #1 got: 6
Producer #1 put: 7
Consumer #1 got: 7
Producer #1 put: 8
Consumer #1 got: 8
Producer #1 put: 9
Consumer #1 got: 9

获取线程状态

以下示例演示了如何使用Thread的isAlive()&getStatus()方法显示线程的不同状态。

class MyThread extends Thread {
   boolean waiting = true;
   boolean ready = false;
   MyThread() {
   }
   public void run() {
	  String thrdName = Thread.currentThread().getName();
	  System.out.println(thrdName + " starting.");
	  
	  while(waiting) System.out.println("waiting:"+waiting);
	  System.out.println("waiting...");
	  startWait();
	  try {
		 Thread.sleep(1000);
	  } catch(Exception exc) {
		 System.out.println(thrdName + " interrupted.");
	  }
	  System.out.println(thrdName + " terminating.");
   }
   synchronized void startWait() {
	  try {
		 while(!ready) wait();
	  } catch(InterruptedException exc) {
		 System.out.println("wait() interrupted");
	  }
   }
   synchronized void notice() {
	  ready = true;
	  notify();
   }
}
public class Main {
   public static void main(String args[]) throws Exception {
	  MyThread thrd = new MyThread();
	  thrd.setName("MyThread #1");
	  showThreadStatus(thrd);
	  
	  thrd.start();
	  Thread.sleep(50);
	  showThreadStatus(thrd);
	  
	  thrd.waiting = false;
	  Thread.sleep(50);
	  showThreadStatus(thrd);
	  
	  thrd.notice();
	  Thread.sleep(50);
	  showThreadStatus(thrd);
	  
	  while(thrd.isAlive())
	  System.out.println("alive");
	  showThreadStatus(thrd);
   }
   static void showThreadStatus(Thread thrd) {
	  System.out.println(thrd.getName()+" Alive:"+thrd.isAlive()+" State:" + thrd.getState() );
   }
}

以上代码运行输出结果为

MyThread #1 Alive:false State:NEW
MyThread #1 starting.
waiting:true
waiting:true
alive
alive
MyThread #1 terminating.
alive
MyThread #1 Alive:false State:TERMINATED

获取所有线程

以下示例演示如何使用getName()方法显示所有正在运行的线程的名称。

public class Main extends Thread {
   public static void main(String[] args) {
	  Main t1 = new Main();
	  t1.setName("thread1");
	  t1.start();
	  ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();
	  int noThreads = currentGroup.activeCount();
	  Thread[] lstThreads = new Thread[noThreads];
	  currentGroup.enumerate(lstThreads);
	  
	  for (int i = 0; i < noThreads; i++) System.out.println("Thread No:" + i + " = " + lstThreads[i].getName());
   }
}

以上代码运行输出结果为

Thread No:0 = main
Thread No:1 = thread1

查看线程优先级

以下示例演示如何使用Thread的getPriority()方法检查线程的优先级。

public class Main extends Object {
   private static Runnable makeRunnable() {
	  Runnable r = new Runnable() {
		 public void run() {
			for (int i = 0; i < 5; i++) {
			   Thread t = Thread.currentThread();
			   System.out.println("in run() - priority = " + t.getPriority()+ ", name = " + t.getName());
			   try {
				  Thread.sleep(2000);
			   } catch (InterruptedException x) {}
			}
		 }
	  };
	  return r;
   }
   public static void main(String[] args) {
	  System.out.println(
		 "in main() - Thread.currentThread(). getPriority()=" + Thread.currentThread().getPriority());
	  System.out.println(
		 "in main() - Thread.currentThread().getName()="+ Thread.currentThread().getName());
	  
	  Thread threadA = new Thread(makeRunnable(), "threadA");
	  threadA.start();
	  try {
		 Thread.sleep(3000);
	  } catch (InterruptedException x) {}
	  System.out.println("in main() - threadA.getPriority() = " + threadA.getPriority());
   }
}

以上代码运行输出结果为

in main() - Thread.currentThread().getPriority()=5
in main() - Thread.currentThread().getName()=main
in run() - priority=5, name=threadA
in run() - priority=5, name=threadA
in main() - threadA.getPriority()=5
in run() - priority=5, name=threadA
in run() - priority=5, name=threadA
in run() - priority=5, name=threadA

中断线程

以下示例演示了如何中断线程的正在运行的线程interrupt()方法,并使用isInterrupted()方法检查线程是否中断。

public class GeneralInterrupt extends Object implements Runnable {
   public void run() {
	  try {
		 System.out.println("in run() - about to work2()");
		 work2();
		 System.out.println("in run() - back from work2()");
	  } catch (InterruptedException x) {
		 System.out.println("in run() - interrupted in work2()");
		 return;
	  }
	  System.out.println("in run() - doing stuff after nap");
	  System.out.println("in run() - leaving normally");
   }
   public void work2() throws InterruptedException {
	  while (true) {
		 if (Thread.currentThread().isInterrupted()) {
			System.out.println("C isInterrupted()="+ Thread.currentThread().isInterrupted());
			Thread.sleep(2000);
			System.out.println("D isInterrupted()="+ Thread.currentThread().isInterrupted());
		 }
	  }
   }
   public void work() throws InterruptedException {
	  while (true) {
		 for (int i = 0; i < 100000; i++) {
			int j = i * 2;
		 }
		 System.out.println("A isInterrupted()="+ Thread.currentThread().isInterrupted());
		 if (Thread.interrupted()) {
			System.out.println("B isInterrupted()="+ Thread.currentThread().isInterrupted());
			throw new InterruptedException();
		 }
	  }
   }
   public static void main(String[] args) {
	  GeneralInterrupt si = new GeneralInterrupt();
	  Thread t = new Thread(si);
	  t.start();
	  try {
		 Thread.sleep(2000);
	  } catch (InterruptedException x) { }
		
	  System.out.println("in main() - interrupting other thread");
	  t.interrupt();
	  System.out.println("in main() - leaving");
   }
}

以上代码运行输出结果为

in run() - about to work2()
in main() - interrupting other thread
in main() - leaving
C isInterrupted()=true
in run() - interrupted in work2()

 

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇