【Java】经典示例代码

时间:2023-03-09 05:14:38
【Java】经典示例代码

成鹏致远 | lcw.cnblogs.com | 2014-02-08

单例设计模式

class Singleton{
private static Singleton instance = new Singleton() ; // 在内部产生本类的实例化对象
public static Singleton getInstance(){ // 通过静态方法取得instance对象
return instance ;
}
private Singleton(){ // 将构造方法进行了封装,私有化
}
public void print(){
System.out.println("Hello World!!!") ;
}
};
public class SingletonDemo05{
public static void main(String args[]){
Singleton s1 = null ; // 声明对象
Singleton s2 = null ; // 声明对象
Singleton s3 = null ; // 声明对象
s1 = Singleton.getInstance() ; // 取得实例化对象
s2 = Singleton.getInstance() ; // 取得实例化对象
s3 = Singleton.getInstance() ; // 取得实例化对象
s1.print() ; // 调用方法
s2.print() ; // 调用方法
s3.print() ; // 调用方法
}
};

代理设计模式

interface Network{
public void browse() ; // 浏览
}
class Real implements Network{
public void browse(){
System.out.println("上网浏览信息") ;
}
};
class Proxy implements Network{
private Network network ; // 代理对象
public Proxy(Network network){
this.network = network ;
}
public void check(){
System.out.println("检查用户是否合法。") ;
}
public void browse(){
this.check() ;
this.network.browse() ; // 调用真实的主题操作
}
};
public class ProxyDemo{
public static void main(String args[]){
Network net = null ;
net = new Proxy(new Real()) ;// 指定代理操作
net.browse() ; // 客户只关心上网浏览一个操作
}
};

动态代理设计模式(反射实现)

import java.lang.reflect.InvocationHandler ;
import java.lang.reflect.Proxy ;
import java.lang.reflect.Method ;
interface Subject{
public String say(String name,int age) ; // 定义抽象方法say
}
class RealSubject implements Subject{ // 实现接口
public String say(String name,int age){
return "姓名:" + name + ",年龄:" + age ;
}
};
class MyInvocationHandler implements InvocationHandler{
private Object obj ;
public Object bind(Object obj){
this.obj = obj ; // 真实主题类
return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),this) ;
}
public Object invoke(Object proxy,Method method,Object[] args) throws Throwable{
Object temp = method.invoke(this.obj,args) ; // 调用方法
return temp ;
}
};
public class DynaProxyDemo{
public static void main(String args[]){
Subject sub = (Subject)new MyInvocationHandler().bind(new RealSubject()) ;
String info = sub.say("成鹏致远",2) ;
System.out.println(info) ;
}
};

工厂设计模式

interface Fruit{    // 定义一个水果接口
public void eat() ; // 吃水果
}
class Apple implements Fruit{
public void eat(){
System.out.println("** 吃苹果。") ;
}
};
class Orange implements Fruit{
public void eat(){
System.out.println("** 吃橘子。") ;
}
};
class Factory{ // 定义工厂类
public static Fruit getInstance(String className){
Fruit f = null ;
if("apple".equals(className)){ // 判断是否要的是苹果的子类
f = new Apple() ;
}
if("orange".equals(className)){ // 判断是否要的是橘子的子类
f = new Orange() ;
}
return f ;
}
};
public class InterfaceCaseDemo05{
public static void main(String args[]){
Fruit f = Factory.getInstance(args[0]) ; // 实例化接口
if(f!=null){ // 判断是否取得实例
f.eat() ;
}
}
};

高级工厂设计模式(反射实现)

import java.util.Properties ;
import java.io.File ;
import java.io.FileOutputStream ;
import java.io.FileInputStream ;
interface Fruit{
public void eat() ; // 吃水果
}
class Apple implements Fruit{
public void eat(){ // 覆写eat()方法
System.out.println("** 吃苹果");
}
};
class Orange implements Fruit{
public void eat(){
System.out.println("** 吃橘子") ;
}
};
class Init{
public static Properties getPro(){
Properties pro = new Properties() ;
File f = new File("d:\\fruit.properties") ; // 找到属性文件
try{
if(f.exists()){ // 文件存在
pro.load(new FileInputStream(f)) ; // 读取属性
}else{
pro.setProperty("apple","org.lcw.factorydemo.Apple") ;
pro.setProperty("orange","org.lcw.factorydemo.Orange") ;
pro.store(new FileOutputStream(f),"FRUIT CLASS") ;
}
}catch(Exception e){}
return pro ;
}
};
class Factory{
public static Fruit getInstance(String className){
Fruit fruit = null ;
try{
fruit = (Fruit)Class.forName(className).newInstance() ;
}catch(Exception e){
e.printStackTrace() ;
}
return fruit ;
}
};
public class FactoryDemo{
public static void main(String args[]){
Properties pro = Init.getPro() ;
Fruit f = Factory.getInstance(pro.getProperty("apple")) ;
if(f!=null){
f.eat() ;
}
}
};

适配器设计模式

interface Window{        // 定义Window接口,表示窗口操作
public void open() ; // 打开
public void close() ; // 关闭
public void activated() ; // 窗口活动
public void iconified() ; // 窗口最小化
public void deiconified();// 窗口恢复大小
}
abstract class WindowAdapter implements Window{
public void open(){} ; // 打开
public void close(){} ; // 关闭
public void activated(){} ; // 窗口活动
public void iconified(){} ; // 窗口最小化
public void deiconified(){};// 窗口恢复大小
};
class WindowImpl extends WindowAdapter{
public void open(){
System.out.println("窗口打开。") ;
}
public void close(){
System.out.println("窗口关闭。") ;
}
};
public class AdapterDemo{
public static void main(String args[]){
Window win = new WindowImpl() ;
win.open() ;
win.close() ;
}
};

观察者设计模式

import java.util.* ;
class House extends Observable{ // 表示房子可以被观察
private float price ;// 价钱
public House(float price){
this.price = price ;
}
public float getPrice(){
return this.price ;
}
public void setPrice(float price){
// 每一次修改的时候都应该引起观察者的注意
super.setChanged() ; // 设置变化点
super.notifyObservers(price) ;// 价格被改变
this.price = price ;
}
public String toString(){
return "房子价格为:" + this.price ;
}
};
class HousePriceObserver implements Observer{
private String name ;
public HousePriceObserver(String name){ // 设置每一个购房者的名字
this.name = name ;
}
public void update(Observable o,Object arg){
if(arg instanceof Float){
System.out.print(this.name + "观察到价格更改为:") ;
System.out.println(((Float)arg).floatValue()) ;
}
}
};
public class ObserDemo01{
public static void main(String args[]){
House h = new House(1000000) ;
HousePriceObserver hpo1 = new HousePriceObserver("购房者A") ;
HousePriceObserver hpo2 = new HousePriceObserver("购房者B") ;
HousePriceObserver hpo3 = new HousePriceObserver("购房者C") ;
h.addObserver(hpo1) ;
h.addObserver(hpo2) ;
h.addObserver(hpo3) ;
System.out.println(h) ; // 输出房子价格
h.setPrice(666666) ; // 修改房子价格
System.out.println(h) ; // 输出房子价格
}
};

反射获取类中方法

import java.lang.reflect.Method ;    // 导入构造方法的包
import java.lang.reflect.Modifier ; // 导入构造方法的包
public class TestJava{
public static void main(String args[]){
Class<?> c1 = null ; // 声明Class对象
try{
c1 = Class.forName("java.lang.Math") ; // 实例化对象
}catch(ClassNotFoundException e){
e.printStackTrace() ;
}
Method m[] = c1.getMethods() ; // 取得全部方法
for(int i=0;i<m.length;i++){
Class<?> r = m[i].getReturnType() ; // 得到返回值类型
Class<?> p[] = m[i].getParameterTypes() ; // 取得全部参数的类型
int xx = m[i].getModifiers() ; // 得到修饰符
System.out.print(Modifier.toString(xx) + " ") ; // 输出修饰符
System.out.print(r + " ") ;
System.out.print(m[i].getName()) ;
System.out.print("(") ;
for(int j=0;j<p.length;j++){
System.out.print(p[j].getName() + " " + "arg" + j) ;
if(j<p.length-1){
System.out.print(",") ;
}
}
Class<?> ex[] = m[i].getExceptionTypes() ; // 取出异常
if(ex.length>0){
System.out.print(") throws ") ;
}else{
System.out.print(")") ;
}
for(int j=0;j<ex.length;j++){
System.out.print(ex[j].getName()) ;
if(j<p.length-1){
System.out.print(",") ;
}
}
System.out.println() ;
}
}
};

反射获取类中属性

import java.lang.reflect.Field ;    // 导入构造方法的包
import java.lang.reflect.Modifier ; // 导入构造方法的包
public class TestJava{
public static void main(String args[]){
Class<?> c1 = null ; // 声明Class对象
try{
c1 = Class.forName("java.lang.Math") ; // 实例化对象
}catch(ClassNotFoundException e){
e.printStackTrace() ;
}
{ // 本类属性
Field f[] = c1.getDeclaredFields() ; // 取得本类中的属性
for(int i=0;i<f.length;i++){
Class<?> r = f[i].getType() ; // 得到属性类型
int mo = f[i].getModifiers() ; // 得到修饰符的数字
String priv = Modifier.toString(mo) ; // 还原修饰符
System.out.print("本类属性:") ;
System.out.print(priv + " ") ;
System.out.print(r.getName() + " ") ; // 得到属性类型
System.out.print(f[i].getName()) ; // 输出属性名称
System.out.println(" ;") ;
}
}
{ // 公共属性
Field f[] = c1.getFields() ; // 取得本类中的公共属性
for(int i=0;i<f.length;i++){
Class<?> r = f[i].getType() ; // 得到属性类型
int mo = f[i].getModifiers() ; // 得到修饰符的数字
String priv = Modifier.toString(mo) ; // 还原修饰符
System.out.print("公共属性:") ;
System.out.print(priv + " ") ;
System.out.print(r.getName() + " ") ; // 得到属性类型
System.out.print(f[i].getName()) ; // 输出属性名称
System.out.println(" ;") ;
}
}
}
};

反射修改类中属性

import java.lang.reflect.Field ;
public class InvokeFieldDemo{
public static void main(String args[]) throws Exception{
Class<?> c1 = null ;
Object obj = null ;
c1 = Class.forName("org.lcw.invoke.Person") ; // 实例化Class对象
obj = c1.newInstance() ;
Field nameField = null ;
Field ageField = null ;
nameField = c1.getDeclaredField("name") ; // 取得name属性
ageField = c1.getDeclaredField("age") ; // 取得name属性
nameField.setAccessible(true) ; // 此属性对外部可见
ageField.setAccessible(true) ; // 此属性对外部可见
nameField.set(obj,"成鹏致远") ; // 设置name属性内容
ageField.set(obj,2) ; // 设置age属性内容
System.out.println("姓名:" + nameField.get(obj)) ;
System.out.println("年龄:" + ageField.get(obj)) ;
}
}; /*
package org.lcw.invoke ;
public class Person
private String name ;
private int age ;
public Person(){ // 无参构造
}
public Person(String name,int age){
this(name) ;
this.age = age ;
}
public void setName(String name){
this.name = name ;
}
public void setAge(int age){
this.age = age ;
}
public String getName(){
return this.name ;
}
public int getAge(){
return this.age ;
}
};
*/

反射Setter修改类中属性

import java.lang.reflect.Method ;
public class InvokeSetGet{
public static void main(String args[]){
Class<?> c1 = null ;
Object obj = null ;
try{
c1 = Class.forName("org.lcw.invoke.Person") ; // 实例化Class对象
}catch(Exception e){}
try{
obj = c1.newInstance() ;
}catch(Exception e){}
setter(obj,"name","成鹏致远",String.class) ; // 调用setter方法
setter(obj,"age",2,int.class) ; // 调用setter方法
System.out.print("姓名:") ;
getter(obj,"name") ;
System.out.print("年龄:") ;
getter(obj,"age");
}
/**
Object obj:要操作的对象
String att:要操作的属性
Object value:要设置的属性内容
Class<?> type:要设置的属性类型
*/
public static void setter(Object obj,String att,Object value,Class<?> type){
try{
Method met = obj.getClass().getMethod("set"+initStr(att),type) ; // 得到setter方法
met.invoke(obj,value) ; // 设置setter的内容
}catch(Exception e){
e.printStackTrace() ;
}
}
public static void getter(Object obj,String att){
try{
Method met = obj.getClass().getMethod("get"+initStr(att)) ; // 得到setter方法
System.out.println(met.invoke(obj)) ; // 调用getter取得内容
}catch(Exception e){
e.printStackTrace() ;
}
}
public static String initStr(String old){ // 将单词的首字母大写
String str = old.substring(0,1).toUpperCase() + old.substring(1) ;
return str ;
}
}; /*
package org.lcw.invoke ;
public class Person
private String name ;
private int age ;
public Person(){ // 无参构造
}
public Person(String name,int age){
this(name) ;
this.age = age ;
}
public void setName(String name){
this.name = name ;
}
public void setAge(int age){
this.age = age ;
}
public String getName(){
return this.name ;
}
public int getAge(){
return this.age ;
}
};
*/

经典二叉树排序算法

class BinaryTree
{
class Node
{ // 声明一个节点类
private Comparable data; // 保存具体的内容
private Node left; // 保存左子树
private Node right; // 保存右子树 public Node(Comparable data)
{
this.data = data;
} public void addNode(Node newNode)
{
// 确定是放在左子树还是右子树
if (newNode.data.compareTo(this.data) < 0)
{ // 内容小,放在左子树
if (this.left == null)
{
this.left = newNode; // 直接将新的节点设置成左子树
}
else
{
this.left.addNode(newNode); // 继续向下判断
}
}
if (newNode.data.compareTo(this.data) >= 0)
{ // 放在右子树
if (this.right == null)
{
this.right = newNode; // 没有右子树则将此节点设置成右子树
}
else
{
this.right.addNode(newNode); // 继续向下判断
}
}
} public void printNode()
{ // 输出的时候采用中序遍历
if (this.left != null)
{
this.left.printNode(); // 输出左子树
}
System.out.print(this.data + "\t");
if (this.right != null)
{
this.right.printNode();
}
}
}; private Node root; // 根元素 public void add(Comparable data)
{ // 加入元素
Node newNode = new Node(data); // 定义新的节点
if (root == null)
{ // 没有根节点
root = newNode; // 第一个元素作为根节点
}
else
{
root.addNode(newNode); // 确定是放在左子树还是放在右子树
}
} public void print()
{
this.root.printNode(); // 通过根节点输出
}
}; public class ComparableDemo03
{
public static void main(String args[])
{
BinaryTree bt = new BinaryTree();
bt.add(8);
bt.add(3);
bt.add(3);
bt.add(10);
bt.add(9);
bt.add(1);
bt.add(5);
bt.add(5);
System.out.println("排序之后的结果:");
bt.print();
}
};

经典链表操作算法

class Link{        // 链表的完成类
class Node{ // 保存每一个节点,此处为了方便直接定义成内部类
private String data ; // 保存节点的内容
private Node next ; // 保存下一个节点
public Node(String data){
this.data = data ; // 通过构造方法设置节点内容
}
public void add(Node newNode){ // 将节点加入到合适的位置
if(this.next==null){ // 如果下一个节点为空,则把新节点设置在next的位置上
this.next = newNode ;
}else{ // 如果不为空,则需要向下继续找next
this.next.add(newNode) ;
}
}
public void print(){
System.out.print(this.data + "\t") ; // 输出节点内容
if(this.next!=null){ // 还有下一个元素,需要继续输出
this.next.print() ; // 下一个节点继续调用print
}
}
public boolean search(String data){ // 内部搜索的方法
if(data.equals(this.data)){ // 判断输入的数据是否和当前节点的数据一致
return true ;
}else{ // 向下继续判断
if(this.next!=null){ // 下一个节点如果存在,则继续查找
return this.next.search(data) ; // 返回下一个的查询结果
}else{
return false ; // 如果所有的节点都查询完之后,没有内容相等,则返回false
}
}
}
public void delete(Node previous,String data){
if(data.equals(this.data)){ // 找到了匹配的节点
previous.next = this.next ; // 空出当前的节点
}else{
if(this.next!=null){ // 还是存在下一个节点
this.next.delete(this,data) ; // 继续查找
}
}
}
};
private Node root ; // 链表中必然存在一个根节点
public void addNode(String data){ // 增加节点
Node newNode = new Node(data) ; // 定义新的节点
if(this.root==null){ // 没有根节点
this.root = newNode ; // 将第一个节点设置成根节点
}else{ // 不是根节点,放到最后一个节点之后
this.root.add(newNode) ; // 通过Node自动安排此节点放的位置
}
}
public void printNode(){ // 输出全部的链表内容
if(this.root!=null){ // 如果根元素不为空
this.root.print() ; // 调用Node类中的输出操作
}
}
public boolean contains(String name){ // 判断元素是否存在
return this.root.search(name) ; // 调用Node类中的查找方法
}
public void deleteNode(String data){ // 删除节点
if(this.contains(data)){ // 判断节点是否存在
// 一定要判断此元素现在是不是根元素相等的
if(this.root.data.equals(data)){ // 内容是根节点
this.root = this.root.next ; // 修改根节点,将第一个节点设置成根节点
}else{
this.root.next.delete(root,data) ; // 把下一个节点的前节点和数据一起传入进去
}
}
}
};
public class LinkDemo02{
public static void main(String args[]){
Link l = new Link() ;
l.addNode("A") ; // 增加节点
l.addNode("B") ; // 增加节点
l.addNode("C") ; // 增加节点
l.addNode("D") ; // 增加节点
l.addNode("E") ; // 增加节点
System.out.println("======= 删除之前 ========") ;
l.printNode() ;
// System.out.println(l.contains("X")) ;
l.deleteNode("C") ; // 删除节点
l.deleteNode("D") ; // 删除节点
l.deleteNode("A") ; // 删除节点
System.out.println("\n====== 删除之后 =========") ;
l.printNode() ;
System.out.println("\n查询节点:" + l.contains("B")) ;
}
};

经典生产者与消费者算法(多线程同步互斥)

class Info
{ // 定义信息类
private String name = "成鹏致远"; // 定义name属性
private String content = "学生"; // 定义content属性
private boolean flag = false; // 设置标志位 public synchronized void set(String name, String content)
{
if (!flag)
{
try
{
super.wait();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
this.setName(name); // 设置名称
try
{
Thread.sleep(300);
} catch (InterruptedException e)
{
e.printStackTrace();
}
this.setContent(content); // 设置内容
flag = false; // 改变标志位,表示可以取走
super.notify();
} public synchronized void get()
{
if (flag)
{
try
{
super.wait();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
try
{
Thread.sleep(300);
} catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(this.getName() + " --> " + this.getContent());
flag = true; // 改变标志位,表示可以生产
super.notify();
} public void setName(String name)
{
this.name = name;
} public void setContent(String content)
{
this.content = content;
} public String getName()
{
return this.name;
} public String getContent()
{
return this.content;
}
}; class Producer implements Runnable
{ // 通过Runnable实现多线程
private Info info = null; // 保存Info引用 public Producer(Info info)
{
this.info = info;
} public void run()
{
boolean flag = false; // 定义标记位
for (int i = 0; i < 50; i++)
{
if (flag)
{
this.info.set("个人博客", "http://lcw.cnblogs.com"); // 设置名称
flag = false;
}
else
{
this.info.set("个人网站", "http://infodown.tap.cn"); // 设置名称
flag = true;
}
}
}
}; class Consumer implements Runnable
{
private Info info = null; public Consumer(Info info)
{
this.info = info;
} public void run()
{
for (int i = 0; i < 50; i++)
{
this.info.get();
}
}
}; public class Test_Format
{
public static void main(String args[])
{
Info info = new Info(); // 实例化Info对象
Producer pro = new Producer(info); // 生产者
Consumer con = new Consumer(info); // 消费者
new Thread(pro).start();
new Thread(con).start();
}
};

String对正则表达式的支持

import java.util.regex.Pattern ;
import java.util.regex.Matcher ;
public class RegexDemo06{
public static void main(String args[]){
String str1 = "A1B22C333D4444E55555F".replaceAll("\\d+","_") ;
boolean temp = "1983-07-27".matches("\\d{4}-\\d{2}-\\d{2}") ;
String s[] = "A1B22C333D4444E55555F".split("\\d+") ;
System.out.println("字符串替换操作:" + str1) ;
System.out.println("字符串验证:" + temp) ;
System.out.print("字符串的拆分:") ;
for(int x=0;x<s.length;x++){
System.out.print(s[x] + "\t") ;
}
}
};

代码块说明

class Demo{
{ // 直接在类中编写代码块,称为构造块
System.out.println("1、构造块。") ;
}
static{ // 使用static,称为静态代码块
System.out.println("0、静态代码块") ;
}
public Demo(){ // 定义构造方法
System.out.println("2、构造方法。") ;
}
};
public class CodeDemo03{
static{ // 在主方法所在的类中定义静态块
System.out.println("在主方法所在类中定义的代码块") ;
}
public static void main(String args[]){
new Demo() ; // 实例化对象
new Demo() ; // 实例化对象
new Demo() ; // 实例化对象
}
};

取得当前时间最简便算法

import java.util.*; // 导入需要的工具包
import java.text.*; // 导入SimpleDateFormat所在的包 class DateTime
{ // 以后直接通过此类就可以取得日期时间
private SimpleDateFormat sdf = null; // 声明SimpleDateFormat对象 public String getDate()
{ // 得到的是一个日期:格式为:yyyy-MM-dd HH:mm:ss.SSS
this.sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
return this.sdf.format(new Date());// 将当前日期进行格式化操作
} public String getDateComplete()
{ // 得到的是一个日期:格式为:yyyy年MM月dd日 HH时mm分ss秒SSS毫秒
this.sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒SSS毫秒");
return this.sdf.format(new Date());// 将当前日期进行格式化操作
} public String getTimeStamp()
{ // 得到的是一个时间戳
this.sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
return this.sdf.format(new Date());// 将当前日期进行格式化操作
}
}; public class DateDemo07
{
public static void main(String args[])
{
DateTime dt = new DateTime();
System.out.println("系统日期:" + dt.getDate());
System.out.println("中文日期:" + dt.getDateComplete());
System.out.println("时间戳:" + dt.getTimeStamp());
}
};

字节流文件拷贝算法

import java.io.* ;
public class Copy{
public static void main(String args[]){
if(args.length!=2){ // 判断是否是两个参数
System.out.println("输入的参数不正确。") ;
System.out.println("例:java Copy 源文件路径 目标文件路径") ;
System.exit(1) ; // 系统退出
}
File f1 = new File(args[0]) ; // 源文件的File对象
File f2 = new File(args[1]) ; // 目标文件的File对象
if(!f1.exists()){
System.out.println("源文件不存在!") ;
System.exit(1) ;
}
InputStream input = null ; // 准备好输入流对象,读取源文件
OutputStream out = null ; // 准备好输出流对象,写入目标文件
try{
input = new FileInputStream(f1) ;
}catch(FileNotFoundException e){
e.printStackTrace() ;
}
try{
out = new FileOutputStream(f2) ;
}catch(FileNotFoundException e){
e.printStackTrace() ;
}
if(input!=null && out!=null){ // 判断输入或输出是否准备好
int temp = 0 ;
try{
while((temp=input.read())!=-1){ // 开始拷贝
out.write(temp) ; // 边读边写
}
System.out.println("拷贝完成!") ;
}catch(IOException e){
e.printStackTrace() ;
System.out.println("拷贝失败!") ;
}
try{
input.close() ; // 关闭
out.close() ; // 关闭
}catch(IOException e){
e.printStackTrace() ;
}
}
}
}

菜单选择类设计方法

public class Menu{
public Menu(){
while(true){
this.show() ; // 无限制调用菜单的显示
}
}
public void show(){
System.out.println("===== Xxx系统 =====") ;
System.out.println(" [1]、增加数据") ;
System.out.println(" [2]、删除数据") ;
System.out.println(" [3]、修改数据") ;
System.out.println(" [4]、查看数据") ;
System.out.println(" [0]、系统退出\n") ;
InputData input = new InputData() ;
int i = input.getInt("请选择:","请输入正确的选项!") ;
switch(i){
case 1:{
Operate.add() ; // 调用增加操作
break ;
}
case 2:{
Operate.delete() ; // 调用删除操作
break ;
}
case 3:{
Operate.update() ; // 调用更新操作
break ;
}
case 4:{
Operate.find() ; // 调用查看操作
break ;
}
case 0:{
System.exit(1) ; // 系统退出
break ;
}
default:{
System.out.println("请选择正确的操作!") ;
}
}
}
};

列出指定目录所有文件方法

import java.io.File ;
import java.io.IOException ;
public class FileDemo11{
public static void main(String args[]){
File my = new File("d:" + File.separator) ; // 操作路径
print(my) ;
}
public static void print(File file){ // 递归调用
if(file!=null){ // 判断对象是否为空
if(file.isDirectory()){ // 如果是目录
File f[] = file.listFiles() ; // 列出全部的文件
if(f!=null){ // 判断此目录能否列出
for(int i=0;i<f.length;i++){
print(f[i]) ; // 因为给的路径有可能是目录,所以,继续判断
}
}
}else{
System.out.println(file) ; // 输出路径
}
}
}
};