System类、Object类、Arrays类、Cloneable接口
- <span style="font-size:16px;">package test;
- public class SystemDemo {
- public static void main(String[] args) {
- String[] s = new String[] { "liu" };
- String[] s2 = new String[] { "hai" };
- String[][] a = { s, s2, s, s, s, s2, s2, s };
- String[][] b = new String[10][10];
- /*
- * System类包含一些有用的类字段和方法,是final类,无法被继承,构造方法是private,不能创建System对象。
- * 所有public属性和方法都是final static
- */
- // 1.数组复制,采用本地方法复制,实现了深拷贝
- System.arraycopy(a, 1, b, 0, 5);
- System.out.println(b[0][0]);
- // 2.已经过去的毫米数,从1970-1-1开始
- System.currentTimeMillis();
- // 3.提示虚拟机进行垃圾回收,通过调用Runtime.getRuntime().gc();实现
- System.gc();
- // 4.返回系统环境
- System.getenv();
- // 5.返回当前的系统属性。
- System.getProperties();
- // 6.可用於計數已過去的時間
- System.nanoTime();
- // 7.0表示正常退出,調用Runtime.getRuntime().exit(0);
- System.exit(0);
- // 8.返回给定对象的哈希码,该代码与默认的方法 hashCode() 返回的代码一样,无论给定对象的类是否重写 hashCode()。
- System.identityHashCode(null);
- }
- }
- </span>
- <span style="font-size:16px;">package test;
- public class ObjectDemo {
- /*
- * 1.Object没有public 的静态属性和方法
- * 2.public final native Class<?> getClass()返回运行时类信息,
- * 3.toString 返回类名+@+哈希码值
- * 4.其中wait和notify方法是final的,不可继承
- * 5.equals方法只比较对象的引用,hashCode方法返回哈希码值。
- * 6.重写equals方法要重写hashCode,因为相同的对象(通过equals比较返回true)
- * 必须返回相同的哈希码。
- * 7.finalize方法是一个protected空方法
- * 8.protected native Object clone()返回一个副本,对象必须实现Cloneable接口
- */
- }
- </span>
- <span style="font-size:16px;">package test;
- import java.util.Arrays;
- public class ArraysDemo {
- /*
- * 1.数组类提供了排序功能,对基本数据类型length<7采用直接插入排序,否则采用快速排序 如果数组元素时对象,采用合并排序
- * 2.提供二分查找法实现,注意二分查找时先对数组进行排序,否则返回一个不确定值
- */
- public static void main(String[] args) {
- int[][] a = { { 1, 2 } };
- int[][] b = { { 1, 2 } };
- System.out.println(Arrays.toString(a));
- // 3. 多维数组的toString
- System.out.println(Arrays.deepToString(a));
- System.out.println(Arrays.hashCode(a));
- System.out.println(Arrays.deepHashCode(a));
- System.out.println(Arrays.equals(a, b));
- // 4. 多维数组的比较
- System.out.println(Arrays.deepEquals(a, b));
- // 5. 并没有实现多维数组的复制
- int[][] c = Arrays.copyOf(a, 1);
- // 6.填充数组
- Arrays.fill(a[0], 5);// 在此改变a的值影响到了数组c的值
- System.out.println(Arrays.deepToString(c));
- System.out.println(Arrays.equals(a, c));
- System.out.println(Arrays.deepEquals(a, c));
- }
- }
- </span>
- <span style="font-size:16px;">package test;
- public class DeepCloneDemo {
- public static void main(String[] args) {
- B b = new B(2, new A(1));
- B b1 = (B) b.clone();
- System.out.println(b == b1);
- System.out.println(b.equals(b1));
- System.out.println(b.getClass() == b.getClass());
- System.out.println("改变b的副本b1前:y=" + b.getY() + ",x=" + b.getA().getX());
- b1.setY(5);
- b1.getA().setX(100);
- System.out.println("改变b的副本b1后:y=" + b.getY() + ",x=" + b.getA().getX());
- System.out.println("深克隆成功!!!");
- }
- }
- class A implements Cloneable {
- private int x;
- // 为了实现深克隆
- public Object clone() {
- A a = null;
- try {
- a = (A) super.clone();
- } catch (CloneNotSupportedException e) {
- e.printStackTrace();
- }
- return a;
- }
- public A(int x) {
- this.x = x;
- }
- public int getX() {
- return x;
- }
- public void setX(int x) {
- this.x = x;
- }
- }
- class B implements Cloneable {
- private int y;
- private A a;
- // 覆盖Object中clone方法
- // protected native Object clone() throws CloneNotSupportedException;
- // 注意到protected,这里把权限改为了public
- public Object clone() {
- B b = null;
- try {
- b = (B) super.clone();
- // 实现深克隆,没有这条语句只是克隆了a的引用
- b.a = (A) a.clone();
- } catch (CloneNotSupportedException e) {
- e.printStackTrace();
- }
- return b;
- }
- public B(int y, A a) {
- this.y = y;
- this.a = a;
- }
- public int getY() {
- return y;
- }
- public A getA() {
- return a;
- }
- public void setY(int y) {
- this.y = y;
- }
- public void setA(A a) {
- this.a = a;
- }
- }
- </span>
InputStream的作用是用来表示那些从不同数据源产生输入的类。OutputStream决定了输出所要去往的目标
数据源 对应的类(都继承自InputStream)
(1)字节数组 ByteArrayInputStream [ByteArrayOutputStream]
(2)String对象 StringBufferInputStream(已弃用)
(3)文件 FileInputStream [FileOutputStream]
(4)“管道” PipedInputStream [PipedOutputStream]
(5)由其它种类的流组成的序列 SequenceInputStream
(6)其他数据源,如Internet
示例:
- <span style="font-size:16px;">package test;
- import java.io.ByteArrayInputStream;
- import java.io.ByteArrayOutputStream;
- import java.util.Arrays;
- /*
- * ByteArrayInputStream(ByteArrayOutputStream)表示从字节数组产生输入(输出)
- * 这个类其实就是对一个字节数组进行操作,把这个字节数组看成一个缓冲区
- * 关闭方法是一个空方法,关闭后不影响其他方法
- * 可以将数组定位到指定位置开始读/写,可以将数组从头开始读/写,可以查看数组还有几个字节可用
- * 可以在某个位置做标记,可以返回到标记位置进行读/写
- */
- public class ByteArrayInputStreamDemo {
- public static void main(String[] args) {
- // 输入流缓冲区(假设已经有若干字节)
- byte[] inputBuff = new byte[] { 1, 2, 3, 'a', 'b', 'c', 'd', 'e', 'f' };
- byte[] result = new byte[20];
- ByteArrayInputStream inputStream = new ByteArrayInputStream(inputBuff);
- // 将缓冲区的字节读入result数组并输出result
- inputStream.read(result, 0, 20);
- System.out.println(Arrays.toString(result));
- // 将result数组写入输出流
- ByteArrayOutputStream outStream = new ByteArrayOutputStream();
- outStream.write(result, 0, 20);
- System.out.println(Arrays.toString(outStream.toByteArray()));
- }
- }
- </span>
- <span style="font-size:16px;">package test;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- /*
- * FileInputStream从文件中产生输入流,FileOutputStream
- * 把输出流输出到文件。读/写、打开和关闭都是调用本地方法
- */
- public class FileInputStreamDemo {
- public static void main(String[] args) throws IOException {
- FileInputStream inputStream = null;
- try {
- inputStream = new FileInputStream(new File("file/bb.dat"));
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- // 读到一个字节数组
- byte[] result = new byte[500];
- // int b;
- // while ((b = inputStream.read()) != -1)//读一个字节
- // System.out.print((char) b);
- inputStream.read(result);
- // System.out.println(Arrays.toString(result));
- inputStream.close();
- FileOutputStream outputStream = null;
- // true表示以追加的形式打开
- outputStream = new FileOutputStream("file/bb.dat", true);
- // 写入
- outputStream.write((int) 'A');
- outputStream.write(result);
- outputStream.close();
- }
- }
- </span>
java IO系统采用装饰器模式,用一些装饰类来装饰输入输出来,提供更强大的IO操作
FilterInputStream(FilterOutputStream)继承自InputStream(Outputstream)
常用装饰类(都继承自FilterInputStream) 功能
DataInputStream(DataOutputStream) 读写基本类型即UTF
BufferedInputStream(BufferedOutputStream) 使用缓冲区
PrintStream继承自Outputstream,用于格式化输出到文本或控制台等
示例:
- <span style="font-size:16px;">package test;
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- /*
- * DataInputStream继承自FilterInputStream(FilterInputStream继承自InputStream)
- * 用来装饰InputStream,提供可移植方式从流读取基本数据类型
- * DataOutputStream继承自FilterOutputStream(FilterOutputStream继承自OutputStream)
- * 用来装饰OutputStream,提供可移植方式向流写入基本数据类型
- * DataInputStream/DataOutputStream可以实现数据的存储与恢复
- */
- public class DataInputStreamDemo {
- public static void main(String[] args) {
- DataOutputStream dataOutStream = null;
- try {
- dataOutStream = new DataOutputStream(new BufferedOutputStream(
- new FileOutputStream("file/aa.data")));
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- try {// 写入文件
- dataOutStream.writeChar('a');
- dataOutStream.writeInt(3);
- dataOutStream.writeDouble(5.5);
- dataOutStream.writeFloat(3.2f);
- dataOutStream.writeUTF("nihaoma");
- dataOutStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- DataInputStream dataInputStream = null;
- try {
- dataInputStream = new DataInputStream(new BufferedInputStream(
- new FileInputStream("file/aa.data")));
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- try {// 读取文件
- System.out.println(dataInputStream.readChar());
- System.out.println(dataInputStream.readInt());
- System.out.println(dataInputStream.readDouble());
- System.out.println(dataInputStream.readFloat());
- System.out.println(dataInputStream.readUTF());
- dataInputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- </span>
- <span style="font-size:16px;">package test;
- import java.io.FileNotFoundException;
- import java.io.PrintStream;
- /*
- * 继承自FilterOutputStream,其中DataOutputStream处理数据的存储,PrintStream处理显示
- * 用于格式化打印
- */
- public class PrintStreamDemo {
- public static void main(String[] args) throws FileNotFoundException {
- // 把数据可视化格式显示到文本文件中
- PrintStream printStream = new PrintStream("file/test2.txt");
- printStream.println('a');
- printStream.println(2);
- printStream.println(3.2);
- printStream.println("liuhaifang");
- printStream.println("刘海房");
- // 可视化显示到控制台
- printStream = new PrintStream(System.out);
- printStream.println("hello java");
- }
- }
- </span>
- package http;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.IOException;
- /*
- * Read和Write分别对应InputStream和OutputStream
- * 前者用于字符流,后者用于字节流
- * FileReader和FileWrite分别对应与FileInputStream和FileOutputStream
- * BufferedReader和BufferedWrite分别对应与BufferedInputStream和
- * BufferedOutputStream
- * 此示例实现文本文件的字符读写
- */
- public class FileReaderAndBufferedReaderDemo {
- public static String read(String fileName) throws IOException {
- StringBuilder str = new StringBuilder();
- BufferedReader in = new BufferedReader(new FileReader(fileName));
- String s;
- while ((s = in.readLine()) != null)
- str.append(s + '\n');
- in.close();
- return str.toString();
- }
- public static void write(String fileName, boolean append)
- throws IOException {
- BufferedWriter out = new BufferedWriter(
- new FileWriter(fileName, append));
- out.write("我是dahai!java hello!");
- out.close();
- }
- public static void main(String[] args) {
- try {
- write("file/test3.txt", false);
- System.out.println(read("file/test3.txt"));
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- package http;
- import java.io.ByteArrayInputStream;
- import java.io.DataInputStream;
- import java.io.IOException;
- /*
- * DataInputStream用于读取格式化的数据
- */
- public class DataInputStreamAndByteArrayInputStreamDemo {
- public static void main(String[] args) throws IOException {
- DataInputStream in = new DataInputStream(new ByteArrayInputStream(
- FileReaderAndBufferedReaderDemo.read("file/test3.txt")
- .getBytes()));
- while (in.available() != 0)
- System.out.print((char) in.readByte());
- }
- }
- package test;
- import http.FileReaderAndBufferedReaderDemo;
- import java.io.IOException;
- import java.io.StringReader;
- /*
- * StringReader操作的是字符串
- */
- public class StringReaderDemo {
- public static void main(String[] args) throws IOException {
- StringReader in = new StringReader(FileReaderAndBufferedReaderDemo
- .read("file/test3.txt"));
- int c;
- while ((c = in.read()) != -1)
- System.out.print((char) c);
- }
- }
- package test;
- import http.FileReaderAndBufferedReaderDemo;
- import java.io.IOException;
- import java.io.PrintWriter;
- /*
- * 对应于PrintStream
- * 用于格式化输出到文件
- */
- public class PrintWriterDemo {
- public static void main(String[] args) throws IOException {
- // 简化的创建方式
- PrintWriter out = new PrintWriter("file/test4.txt");
- // 也可以这样创建: out=new Printer(new BufferedWriter(new
- // FileWriter("file/test4.txt")));
- // 格式化输出到文本
- out.println('a');
- out.println(3);
- out.println(3.5);
- out.print("我爱你!i love you");
- out.close();
- // 从文本读取刚才的写入
- System.out.println(FileReaderAndBufferedReaderDemo
- .read("file/test4.txt"));
- }
- }
- package test;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.io.RandomAccessFile;
- /*
- * RandomAccessFile直接继承Object,可以进行随机输入和输出,类似于c语言的文件操作
- * 要指明以什么方式打开文件,用这个类时要知道文件的排版,该类有读写基本类型和UTF-8字符串
- * 的各种方法,可以定位到文件的某一位置进行读写
- */
- public class RandomAccessFileDemo {
- public static void main(String[] args) throws FileNotFoundException {
- RandomAccessFile out = new RandomAccessFile("file/test5", "rw");
- try {
- out.writeInt(1);
- out.writeDouble(3.3);
- out.writeChar('a');
- out.writeUTF("hello,java!");
- out.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- RandomAccessFile in = new RandomAccessFile("file/test5", "r");
- try {
- in.seek(4);
- System.out.println(in.readDouble());
- in.seek(4+8+2);
- System.out.println(in.readUTF());
- in.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- package test;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- import java.io.Serializable;
- /*
- * ObjectInputStream(ObjectOutputStream)用于对象的序列化
- * 直接对一个对象进行读写,该对象须实现Serializable
- */
- public class ObjectInputStreamDemo {
- public static void writeObject(String fileName, Object o, boolean isAppend)
- throws FileNotFoundException, IOException {
- ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(
- fileName, true));
- out.writeObject(o);
- out.close();
- }
- public static Object readObject(String fileName)
- throws FileNotFoundException, IOException, ClassNotFoundException {
- ObjectInputStream in = new ObjectInputStream(new FileInputStream(
- fileName));
- Object o = in.readObject();
- in.close();
- return o;
- }
- public static void main(String[] args) {
- try {
- ObjectInputStreamDemo.writeObject("file/object", new Person(),
- false);
- ((Person) ObjectInputStreamDemo.readObject("file/object"))
- .display();
- } catch (IOException e) {
- e.printStackTrace();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- class Person implements Serializable {
- private String name = "刘海房liuhaifang";
- private int sex = 0;
- Person(String name, int sex) {
- this.name = name;
- this.sex = sex;
- }
- Person() {
- }
- void display() {
- System.out.println("my name is :" + name);
- String s = (sex == 0) ? "男" : "女";
- System.out.println(s);
- }
- }