`

(源码下载)jdk6.0从入门到精通-----chapter2--输入输出,克隆对象

阅读更多
package formatinout;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class ScannerExample {
	public static void main(String args[]) throws IOException {
		System.out.println("请输入若干个数,每输入一个数用回车确认");
		System.out.println("最后输入一个非数字结束输入操作");

		Scanner reader = new Scanner(System.in); // 标准输入
		double sum = 0;
		int m = 0;
		while (reader.hasNextDouble()) {
			double x = reader.nextDouble();
			m = m + 1;
			sum = sum + x;
		}
		System.out.printf("%d个数的和为%f\n", m, sum);
		System.out.printf("%d个数的平均值是%f\n", m, sum / m); // 格式化输出
		
		
		try {
			FileInputStream fi = new FileInputStream("c:/a.txt");
			
			FileReader fr = new FileReader("c:/a.txt");
			
			FileWriter fw = new FileWriter("c:/a.txt",true);
			
			fw.write(99);    // 写入“c”
			fw.append('x'); //写入"x"
			fw.close(); //必须有,否则写不进去
			
			byte[] buffer = new byte[20];  // zi jie liu
			char[]charbuff = new char[20];        //zi fu liu
			
			try {
				int readchar = fr.read(charbuff);       //zi fu number
				System.out.println(readchar); // h
				for(int i=0;i<readchar;i++)
				System.out.println(charbuff[i]); // h
//				e.....
				fr.close();
				
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			try {
				fi.read(buffer);
				
				String str = new String(buffer);
				System.out.println(str);  //helloworld
				
				for(int i =0;i<buffer.length;i++)
				System.out.println(buffer[i]);  //unicode104
//				101
//				108
//				108
//				111
//				119
//				111
//				114
//				108
//				100
				fi.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
	}
}


一下是一个对象克隆的例子
实体student

package cloneObject;

public class Student [color=red]implements Cloneable [/color]{
	public String id;
	public String name;

	public Object clone() {
		Student o = null;
		try {
			o = (Student) super.clone();
		} catch (Exception e) {
			throw new java.lang.IllegalStateException("Clone 出错!"
					+ e.toString());
		}
		return o;
	}

}


测试类Test
package cloneObject;
public class TestClone {
	
	 public static void main(String[] args) {
		 Student stu1 = new Student();
		 stu1.id="1";
		 stu1.name = "stu1";
		 
		 Student stu2 = (Student) stu1.clone();
		 //对象复制,如果直接用stu2 = stu1;引用的是同一个对象,改变任何一个将对另一个造成影响
		 System.out.println(stu2.id+stu2.name);
		 stu2.id ="2";
		 System.out.println(stu2.id+stu2.name);
		 System.out.println(stu1.id+stu2.name);
	 }
	 
}

结果
1stu1
2stu1
1stu1

源码见附件:
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics