Java学习笔记之IO

一、java.io.File类

1、凡是与输入、输出相关的类、接口等都定义在java.io包下

2、File是一个类,可以由构造器创建其对象。此对象对应着一个文件或文件目录(File既可以是一个文件(.txt .mp3 .xls.  avi .jpg) 也可以是一个文件目录!)

3、File类对象是与平台无关的。 

4、File中的方法,仅涉及到如何创建、删除、重命名等等。只要涉及到文件内容的,FIle是无能为力的,必须由IO流完成。

5、FIle类的对象常作为io流的具体类的构造器的形参。

二、IO流

1、流的分类

按照数据流向的不同:输入流、输出流

按照处理数据的单位不同:字节流、字符流(文本文件)

按照处理数据角色的不同:节点流(直接作用在文件之上)、处理流(除了节点流之外)

2、IO流的体系:

抽象基类:                    节点流(文件流,直接作用于文件)                               缓冲流(处理流的一种)

InputStream                    FileInputStream (int read(byte[] b)                                 BufferedInputStream

OutputStream                 FileOutputStream (void write(b, 0, length)                    BufferedOutputStream(flush())

Reader                            FileReader(int read char[] c)                                           BufferedReader(readLine())

Writer                               FileWriter (void write(c, 0, length))                                  BufferedWriter(flush())

此外还有一个特殊的转换流:

public class TestOtherStream {
	/**
	 * 转换流:InputStreamReader-->OutputStreamWriter
	 * 解码:字符数组-->字符串
	 * 编码:字符串-->字符数组
	 */
	@Test
	public void test() {
		File file = new File("dbcp.txt");
		File file1 = new File("dbcp1.txt");
		BufferedReader br = null;
		BufferedWriter bw = null;
		try {
			FileInputStream fis = new FileInputStream(file);
			FileOutputStream fos = new FileOutputStream(file1);
			InputStreamReader isr = new InputStreamReader(fis, "GBK");
			OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
			br = new BufferedReader(isr);
			bw = new BufferedWriter(osw);
			String str;
			while ((str = br.readLine()) != null) {
				bw.write(str);
				bw.newLine();
				bw.flush();
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if(bw != null) {
				try {
					bw.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}
标准输入输出流的使用:

public class TestInputOutput {
	@Test
	public void test1() {
		BufferedReader br = null;
		try {
			InputStreamReader isr = new InputStreamReader(System.in);
			br = new BufferedReader(isr);
			String str;
			while (true) {
				System.out.println("请输入字符串:");
				str = br.readLine();
				if (str.equalsIgnoreCase("e") || str.equalsIgnoreCase("exit")) {
					break;
				}
				System.out.println(str.toUpperCase());
			}
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}

序列化:

要实现序列化的类必须满足以下条件:

1、要求此类是可以序列化的,实现Serializable接口。

2、要求此类的属性同样要实现Serializable接口。

3、提供一个版本号,public static final long serialVersionUID = 23425124521L;

4、使用static或transient修饰的变量或属性不可实现序列化。

例:

/**
	 * 对象的反序列化过程
	 */
	@Test
	public void test2() {
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new FileInputStream("person.txt"));
			Person p1 = (Person) ois.readObject();
			System.out.println(p1);
			Person p2 = (Person) ois.readObject();
			System.out.println(p2);
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			if (ois != null) {
				try {
					ois.close();
				} catch (IOException e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 对象的序列化过程:将内存中的对象通过ObjectOutputStream转换为二进制流,存储在硬盘文件中。
	 */
	@Test
	public void test1() {
		Person p1 = new Person("小米", 23);
		Person p2 = new Person("红米", 22);
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(new FileOutputStream(new File(
					"person.txt")));
			oos.writeObject(p1);
			oos.flush();
			oos.writeObject(p2);
			oos.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (oos != null) {
				try {
					oos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}

class Person implements Serializable {
	private String name;
	private Integer age;

	/**
	 * @param name
	 * @param age
	 */
	public Person(String name, Integer age) {
		super();
		this.name = name;
		this.age = age;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	}

}


RandomAccessFile类(随机访问文件)

1、既可以充当一个输入流,也可以充当一个输出流。

2、支持从文件的开头读取、写入。

3、支持任意位置读取、写入。

示例代码:

public class TestRandomAccessFile {
	/**
	 * 相较于test3() 更通用。
	 */
	@Test
	public void test4() {
		RandomAccessFile raf = null;
		try {
			raf = new RandomAccessFile(new File("Hello.txt"), "rw");
			raf.seek(4);
			byte[] b = new byte[10];
			int len;
			StringBuffer sb = new StringBuffer();
			while ((len = raf.read(b)) != -1) {
				sb.append(new String(b, 0, len));
			}
			raf.seek(4);
			raf.write("xy".getBytes());
			raf.write(sb.toString().getBytes());
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			if (raf != null) {
				try {
					raf.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 插入效果
	 */
	@Test
	public void test3() {
		RandomAccessFile raf = null;
		try {
			raf = new RandomAccessFile(new File("Hello.txt"), "rw");
			raf.seek(4);
			String str = raf.readLine();
			raf.seek(4);
			raf.write("xy".getBytes());
			raf.write(str.getBytes());
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			if (raf != null) {
				try {
					raf.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 覆盖的效果
	 */
	@Test
	public void test2() {
		RandomAccessFile raf = null;
		try {
			raf = new RandomAccessFile(new File("Hello.txt"), "rw");
			raf.seek(3);
			raf.write("xy".getBytes());
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			if (raf != null) {
				try {
					raf.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 进行文件的读、写
	 */
	@Test
	public void test1() {
		RandomAccessFile raf1 = null;
		RandomAccessFile raf2 = null;
		try {
			raf1 = new RandomAccessFile(new File("dbcp.txt"), "r");
			raf2 = new RandomAccessFile(new File("dbcp2.txt"), "rw");
			byte[] b = new byte[20];
			int length;
			while ((length = raf1.read(b)) != -1) {
				raf2.write(b, 0, length);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (raf2 != null) {
				try {
					raf2.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (raf1 != null) {
				try {
					raf1.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值