[Java]基本的学习实例

类别:Java 点击:0 评论:0 推荐:

好久没有更新了,偷懒,该打!
1、这个是一个基本的文件操作,实现对文件读取、写入一个数字的操作的
package trying;
import java.io.*;

/**
 * @author gooing
 */
public class FileRw {
    private File f = new File("d:\\j2\\a.txt");
    public int getNum(){
        int i = -1;
        try{
            String stri="";
            BufferedReader in = new BufferedReader(new FileReader(f));
            while((stri=in.readLine())!=null){
                i = Integer.parseInt(stri.trim());
            }
            in.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        return i;
    }
    public void setNum(){
        int i = getNum();
        i++;       
        try{
            PrintWriter out=new PrintWriter(new BufferedWriter(new FileWriter(f,false)));           
            out.write(String.valueOf(i)); 
            //可能是编码的原因,如果直接写入int的话,将出现java编码和windows编码的混乱,因此此处写入的是String
            out.close() ;
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        FileRw frw = new FileRw();
        for(int i =0;i<100; i++){
            frw.setNum();
            System.out.println(frw.getNum());
        }
    }
}

2、下面这个是学习工厂模式的一个例子
//Garden.java实现一个抽象花园工厂,你可以从中得到该花园的中心植物和周边植物;
//当然,对于不同的花园而言,其中心植物和周边植物是不一样的
package pkgfactory;

/**
 * @author gooing TODO To change the template for this generated type
 *         comment go to Window - Preferences - Java - Code Style - Code
 *         Templates
 */
public abstract class Garden {
    public abstract Plant getCenter();
    public abstract Plant getBorder();

    public void memo() {
        System.out.println("CenterPlant:" + getCenter().getName());
        System.out.println("BorderPlant:" + getBorder().getName());
        System.out.println("---------------------");
    }
}

//Plant.java 实现对花园中植物的基本抽象,此处只提供一个植物的name属性
package pkgfactory; 
public class Plant {
    public Plant(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    private String name;
}

//VerGarden.java 和FlowerGarden.java 分别实现了一个菜园子和花园子
package pkgfactory;
public class VegGarden extends Garden {
    public Plant getCenter() {
        return new Plant("Wheat");
    }

    public Plant getBorder() {
        return new Plant("Carrot");
    }
}

package pkgfactory;
public class FlowerGarden extends Garden {
    public Plant getCenter() {
        return new Plant("Rose");
    }

    public Plant getBorder() {
        return new Plant("JuHua");
    }
}

//Gardener.java是该例程的一个驱动
package pkgfactory;
public class Gardener {
    public static void main(String[] args) {
        Garden g1 = new FlowerGarden();
        Garden g2 = new VegGarden();
        g1.memo();
        g2.memo();
    }
}


本文地址:http://com.8s8s.com/it/it12333.htm