JavaSE---IO流(其他流)

来源:互联网 发布:淘宝买家炒作如何删除 编辑:程序博客网 时间:2024/05/22 15:45


6.8 其他流

6.8.1 数据输入输出流

    数据输入流:DataInputStream            DataInputStream(InputStream in)

    数据输出流:DataOutputStream        DataOutputStream(OutputStream out)

示例:

import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;/* * 可以读写基本数据类型的数据 * 数据输入流:DataInputStream * DataInputStream(InputStream in) * 数据输出流:DataOutputStream * DataOutputStream(OutputStream out)  */public class DataStreamDemo {public static void main(String[] args) throws IOException {// 写write();// 读read();}public static void read() throws IOException {// 创建数据输入流对象DataInputStream dis = new DataInputStream(new FileInputStream("dos.txt"));byte b = dis.readByte();short s = dis.readShort();int i = dis.readInt();long l = dis.readLong();float f = dis.readFloat();double d = dis.readDouble();char c = dis.readChar();boolean bb = dis.readBoolean();// 释放资源dis.close();System.out.println(b);System.out.println(s);System.out.println(i);System.out.println(l);System.out.println(f);System.out.println(d);System.out.println(c);System.out.println(bb);}public static void write() throws IOException {// 创建数据输出流对象DataOutputStream dos = new DataOutputStream(new FileOutputStream("dos.txt"));// 写数据dos.writeByte(10);dos.writeShort(100);dos.writeInt(1000);dos.writeLong(10000);dos.writeFloat(12.34F);dos.writeDouble(12.56);dos.writeChar('a');dos.writeBoolean(true);// 释放资源dos.close();}}

    运行结果:


6.8.2 内存操作流

    用于处理临时存储信息的,程序结束,数据就从内存中消失。读写完成后,不需要close。

    字节数组:

        ByteArrayInputStream
        ByteArrayOutputStream

    字符数组:

        CharArrayReader

        CharArrayWriter

    字符串:

        StringReader

        StringWriter

示例:

import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;public class ByteArrayStreamDemo {public static void main(String[] args) throws IOException {// 写数据// ByteArrayOutputStream()ByteArrayOutputStream baos = new ByteArrayOutputStream();// 写数据for (int x = 0; x < 10; x++) {baos.write(("hello" + x).getBytes());}//释放资源//通过查看源码,我们知道这里什么都没做,所以不需要close()//baos.close();// public byte[] toByteArray()byte[] bys = baos.toByteArray();//读数据// ByteArrayInputStream(byte[] buf)ByteArrayInputStream bais = new ByteArrayInputStream(bys);int by = 0 ;while((by = bais.read())!=-1){System.out.print((char)by);}//bais.close();}}

    运行结果:


6.8.3 打印流

    |--字节流打印流    PrintStream

    |--字符打印流    PrintWriter

  

    打印流特点:

    1)只有写数据的,没有读取数据。只能操作目的地,不能操作数据源。

    2)可以操作任意类型的数据。

    3)如果启动了自动刷新,能够自动刷新。

    4)该流是可以直接操作文本文件的。

    拓展:哪些流对象是可以直接操作文本文件的呢?

    查流对象的构造方法,如果同时有File类型和String类型的参数,一般来说就是可以直接操作文件的。例如:FileInputStream、FileOutputStream、FileReader、FileWriter、PrintStream、PrintWriter

    示例1:作为Writer的子类使用

import java.io.IOException;import java.io.PrintWriter;public class PrintWriterDemo {public static void main(String[] args) throws IOException {//作为Writer的子类使用PrintWriter pw = new PrintWriter("pw.txt");pw.write("hello");pw.write("world");pw.write("java");pw.close();}}

    运行结果:


    示例2:启动自动刷新

import java.io.FileWriter;import java.io.IOException;import java.io.PrintWriter;/* * 1:可以操作任意类型的数据。 * print() * println() * 2:启动自动刷新 * PrintWriter pw = new PrintWriter(new FileWriter("pw2.txt"), true); * 还是应该调用println()的方法才可以 * 这个时候不仅仅自动刷新了,还实现了数据的换行。 *  * println() *其实等价于于: *bw.write(); *bw.newLine(); *bw.flush(); */public class PrintWriterDemo2 {public static void main(String[] args) throws IOException {// 创建打印流对象//PrintWriter pw = new PrintWriter("pw2.txt");PrintWriter pw = new PrintWriter(new FileWriter("pw2.txt"),true);// write()是搞不定的,怎么办呢?// 我们就应该看看它的新方法// pw.print(true);// pw.print(100);// pw.print("hello");pw.println(true);pw.println(100);pw.println("hello");pw.close();}}

    运行结果:


    示例3:Copy文件

import java.io.BufferedReader;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.io.PrintWriter;/* * 需求:DataStreamDemo.java复制到Copy.java中 * 数据源: * DataStreamDemo.java -- 读取数据 -- FileReader -- BufferedReader * 目的地: * Copy.java -- 写出数据 -- FileWriter -- BufferedWriter -- PrintWriter */public class CopyFileDemo {public static void main(String[] args) throws IOException {// 打印流的改进版// 封装数据源BufferedReader br = new BufferedReader(new FileReader("DataStreamDemo.java"));//封装目的地PrintWriter pw = new PrintWriter(new FileWriter("Copy.java"),true);String line = null;while((line=br.readLine())!=null){pw.println(line);}br.close();pw.close();}}

6.8.4 标准输入输出流

    System类中的两个成员变量:

    public static final InputStream in “标准”输入流。

    public static final PrintStream out “标准”输出流。


    InputStream is = System.in;

    PrintStream ps = System.out;

1. 标准输入流 

    我们已经知道的键盘录入数据包括以下两种:

    1)main方法的args接收参数。

    java HelloWorld hello world java

    2)Scanner(JDK5以后的)

    Scanner sc = new Scanner(System.in);

    String s = sc.nextLine();

    int x = sc.nextInt();

    现在要学习的是标准输入流

    System.in:标准输入流。从键盘获取数据

    示例:使用转换流和标准输入流实现键盘录入数据

public class SystemInDemo {public static void main(String[] args) throws Exception {// 获取标准输入流InputStream is = System.in;// 我要一次获取一行行不行呢?// 行。// 怎么实现呢?// 要想实现,首先你得知道一次读取一行数据的方法是哪个呢?// readLine()// 而这个方法在哪个类中呢?// BufferedReader// 所以,你这次应该创建BufferedReader的对象,但是底层还是的使用标准输入流// BufferedReader br = new BufferedReader(is);// 按照我们的推想,现在应该可以了,但是却报错了// 原因是:字符缓冲流只能针对字符流操作,而你现在是字节流,所以不能是用?// 那么,我还就想使用了,请大家给我一个解决方案?// 把字节流转换为字符流,然后在通过字符缓冲流操作// InputStreamReader isr = new InputStreamReader(is);// BufferedReader br = new BufferedReader(isr);BufferedReader br = new BufferedReader(new InputStreamReader(System.in));System.out.println("请输入一个字符串:");String line = br.readLine();System.out.println("你输入的字符串是:" + line);System.out.println("请输入一个整数:");//int i = Integer.parseInt(br.readLine());line = br.readLine();int i = Integer.parseInt(line);System.out.println("你输入的整数是:" + i);}}

    运行结果:


2.标准输出流

    示例:

public class SystemOutDemo {public static void main(String[] args) {//有这里的讲解我们就知道了,这个输出语句其本质是IO流操作,把数据输出到控制台。System.out.println("helloworld");//获取标准输出流对象PrintStream ps = System.out;ps.println("hellowrold");//ps.print();//这个方法不存在System.out.println();//System.out.print();//所以这个也是错误的}}

    运行结果:


    示例2:使用转换流和标准数据输出流将数据输出到控制台

import java.io.BufferedWriter;import java.io.IOException;import java.io.OutputStream;import java.io.OutputStreamWriter;public class SystemOutDemo2 {public static void main(String[] args) throws IOException {// 获取标准输入流// PrintStream ps = System.out;// OutputStream os = ps;// OutputStream os = System.out;//多态// OutputStreamWriter osw = new OutputStreamWriter(os);// BufferedWriter bw = new BufferedWriter(osw);BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));bw.write("hello");bw.newLine();bw.write("world");bw.newLine();bw.write("java");bw.newLine();bw.flush();bw.close();}}

    运行结果:


6.8.5 随机访问流

    RandomAccessFile类不属于IO包下流,是Object类的子类。但它融合了InputStream和OutputStream的功能,支持对文件的随机访问读取和写入。

    public RandomAccessFile(String name,String mode):第一个参数是文件路径,第二个参数是操作文件的模式。模式有四种,我们最常用的一种叫"rw",这种方式表示我既可以写数据,也可以读取数据 。

    示例:

import java.io.IOException;import java.io.RandomAccessFile;public class RandomAccessFileDemo {public static void main(String[] args) throws IOException {//write();read();}private static void read() throws IOException {//创建随机访问流对象RandomAccessFile raf = new RandomAccessFile("raf.txt","rw");int i = raf.readInt();System.out.println(i);// 该文件指针可以通过 getFilePointer方法读取,并通过 seek 方法设置。System.out.println("当前文件的指针是:"+raf.getFilePointer());char ch = raf.readChar();System.out.println(ch);System.out.println("当前文件的指针是:"+raf.getFilePointer());String s = raf.readUTF();System.out.println(s);System.out.println("当前文件的指针是:"+raf.getFilePointer());// 我不想重头开始了,我就要读取a,怎么办呢?raf.seek(4);ch = raf.readChar();System.out.println(ch);}private static void write() throws IOException {//创建随机访问流对象RandomAccessFile raf = new RandomAccessFile("raf.txt","rw");raf.writeInt(100);raf.writeChar('a');raf.writeUTF("中国");raf.close();}}

    运行结果:


6.8.6 合并流

    SequenceInputStream可以实现多个文件合并成一个文件。

    示例1:两个文件合并成一个文件

import java.io.BufferedOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.SequenceInputStream;/* * 以前的操作: * a.txt -- b.txt * c.txt -- d.txt *  * 现在想要: * a.txt+b.txt -- c.txt */public class SequenceInputStreamDemo {public static void main(String[] args) throws IOException {// SequenceInputStream(InputStream s1, InputStream s2)// 需求:把ByteArrayStreamDemo.java和DataStreamDemo.java的内容复制到Copy.java中InputStream s1 = new FileInputStream("ByteArrayStreamDemo.java");InputStream s2 = new FileInputStream("DataStreamDemo.java");SequenceInputStream sis = new SequenceInputStream(s1,s2);BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("Copy.java"));byte[] bys = new byte[1024];int len = 0;while((len= sis.read(bys))!=-1){bos.write(bys, 0, len);}bos.close();sis.close();}}

    示例2:多个文件合并成一个文件

import java.io.BufferedOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.SequenceInputStream;import java.util.Enumeration;import java.util.Vector;/* * 以前的操作: * a.txt -- b.txt * c.txt -- d.txt * e.txt -- f.txt *  * 现在想要: * a.txt+b.txt+c.txt -- d.txt */public class SequenceInputStreamDemo2 {public static void main(String[] args) throws IOException {// 需求:把下面的三个文件的内容复制到Copy.java中// ByteArrayStreamDemo.java,CopyFileDemo.java,DataStreamDemo.java// SequenceInputStream(Enumeration e)// 通过简单的回顾我们知道了Enumeration是Vector中的一个方法的返回值类型。// Enumeration<E> elements()Vector<InputStream> v = new Vector<InputStream>();InputStream s1 = new FileInputStream("ByteArrayStreamDemo.java");InputStream s2 = new FileInputStream("CopyFileDemo.java");InputStream s3 = new FileInputStream("DataStreamDemo.java");v.add(s1);v.add(s2);v.add(s3);Enumeration<InputStream> en = v.elements();SequenceInputStream sis = new SequenceInputStream(en);BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("Copy.java"));byte[] bys = new byte[1024];int len = 0;while ((len = sis.read(bys)) != -1) {bos.write(bys, 0, len);}bos.close();sis.close();}}

6.8.7 序列化和反序列化流

    序列化流:把对象按照流一样的方式存入文本文件或者在网络中传输。对象 --> 流数据(ObjectOutputStream)

    反序列化流:把文本文件中的流对象数据或者网络中的流对象数据还原成对象。流数据 --> 对象(ObjectInputStream)

    类通过实现 java.io.Serializable 接口以启用其序列化功能。未实现此接口的类将无法使其任何状态序列化或反序列化。该接口没有任何方法,类似于这种没有方法的接口被称为标记接口。

    示例:

import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;/* * NotSerializableException:未序列化异常 *  * 类通过实现 java.io.Serializable 接口以启用其序列化功能。未实现此接口的类将无法使其任何状态序列化或反序列化。 * 该接口居然没有任何方法,类似于这种没有方法的接口被称为标记接口。 *  * java.io.InvalidClassException:  * cn.itcast_07.Person; local class incompatible:  * stream classdesc serialVersionUID = -2071565876962058344,  * local class serialVersionUID = -8345153069362641443 *  * 为什么会有问题呢? * Person类实现了序列化接口,那么它本身也应该有一个标记值。 * 这个标记值假设是100。 * 开始的时候: * Person.class -- id=100 * wirte数据: oos.txt -- id=100 * read数据: oos.txt -- id=100 *  * 现在: * Person.class -- id=200 * wirte数据: oos.txt -- id=100 * read数据: oos.txt -- id=100 * 我们在实际开发中,可能还需要使用以前写过的数据,不能重新写入。怎么办呢? * 回想一下原因是因为它们的id值不匹配。 * 每次修改java文件的内容的时候,class文件的id值都会发生改变。 * 而读取文件的时候,会和class文件中的id值进行匹配。所以,就会出问题。 * 但是呢,如果我有办法,让这个id值在java文件中是一个固定的值,这样,你修改文件的时候,这个id值还会发生改变吗? * 不会。现在的关键是我如何能够知道这个id值如何表示的呢? * 不用担心,你不用记住,也没关系,点击鼠标即可。 * 你难道没有看到黄色警告线吗? *  * 我们要知道的是: * 看到类实现了序列化接口的时候,要想解决黄色警告线问题,就可以自动产生一个序列化id值。 * 而且产生这个值以后,我们对类进行任何改动,它读取以前的数据是没有问题的。 *  * 注意: * 我一个类中可能有很多的成员变量,有些我不想进行序列化。请问该怎么办呢? * 使用transient关键字声明不需要序列化的成员变量 */public class Person implements Serializable {//设置Person.class类的标记值private static final long serialVersionUID = 6558385126777648018L;private String name;//private int age;//使用transient关键字声明不需要序列化的成员变量private transient int age;public Person() {super();}public Person(String name, int age) {super();this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "Person [name=" + name + ", age=" + age + "]";}}public class ObjectStreamDemo {public static void main(String[] args) throws IOException, ClassNotFoundException {// 由于我们要对对象进行序列化,所以我们先自定义一个类// 序列化数据其实就是把对象写到文本文件write();read();}private static void read() throws IOException, ClassNotFoundException {// 创建反序列化对象ObjectInputStream ois = new ObjectInputStream(new FileInputStream("oos.txt"));// 还原对象Object obj = ois.readObject();//输出对象System.out.println(obj);}private static void write() throws IOException {// 创建序列化流对象ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("oos.txt"));// 创建对象Person p = new Person("林青霞", 23);// public final void writeObject(Object obj)oos.writeObject(p);oos.close();}}

    运行结果:


6.8.8 Properties

    Properties:属性集合类。是一个可以和IO流相结合使用的集合类。可保存在流中或从流中加载,属性列表中每个键及其对应值都是一个字符串。

1.基本用法

    Properties继承自Hashtable,说明它可以使用Map的方法

    示例:作为Map使用

import java.util.Properties;import java.util.Set;public class PropertiesDemo {public static void main(String[] args) {// 作为Map集合使用Properties prop = new Properties();// 添加元素prop.put("it002", "hello");prop.put("it001", "world");prop.put("it003", "java");// System.out.println("prop:" + prop);// 遍历集合Set<Object> set = prop.keySet();for (Object key : set) {Object value = prop.get(key);System.out.println(key + "---" + value);}}}

    运行结果:


2. 特殊功能

    public Object setProperty(String key,String value):添加元素

    public String getProperty(String key):获取元素

    public Set<String> stringPropertyNames():获取所有的键的集合

    public void load(Reader reader):把文件中的数据读取到Properties集合中

    public void store(Writer writer,String comments):把Properties集合中的数据存储到文件

    示例1:

import java.util.Properties;import java.util.Set;public class PropertiesDemo2 {public static void main(String[] args) {//创建集合对象Properties prop = new Properties();//添加元素prop.setProperty("张三","30");prop.setProperty("李四","40");prop.setProperty("王五","50");//获取元素// public Set<String> stringPropertyNames():获取所有的键的集合Set<String> set = prop.stringPropertyNames();for(String key:set){String value = prop.getProperty(key);System.out.println(key+"---"+value);}}}/* * class Hashtalbe<K,V> { public V put(K key,V value) { ... } } *  * class Properties extends Hashtable { public V setProperty(String key,String * value) { return put(key,value); } } */

    运行结果:


    示例2:

import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.io.Reader;import java.io.Writer;import java.util.Properties;/* * 这里的集合必须是Properties集合: * public void load(Reader reader):把文件中的数据读取到集合中 * public void store(Writer writer,String comments):把集合中的数据存储到文件 *  * 单机版游戏: * 进度保存和加载。 * 三国群英传,三国志,仙剑奇侠传... *  * 吕布=1 * 方天画戟=1 */public class PropertiesDemo3 {public static void main(String[] args) throws IOException {myLoad();myStore();}private static void myStore() throws IOException {// 创建集合对象Properties prop = new Properties();prop.setProperty("令狐冲", "27");prop.setProperty("林平之", "27");prop.setProperty("任我行", "27");// public void store(Writer writer,String comments):把集合中的数据存储到文件Writer w = new FileWriter("name.txt");prop.store(w,"helloworld");w.close();}private static void myLoad() throws IOException {Properties prop = new Properties();// public void load(Reader reader):把文件中的数据读取到集合中// 注意:这个文件的数据必须是键值对形式Reader r = new FileReader("prop.txt");prop.load(r);r.close();System.out.println("prop:" + prop);}}

    运行结果:


    练习1:我有一个文本文件(user.txt),我知道数据是键值对形式的,但是不知道内容是什么,请写一个程序判断是否有“lisi”这样的键存在,如果有就改变值为”100”。

import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.io.Reader;import java.io.Writer;import java.util.Properties;import java.util.Set;/*  * 分析: * A:把文件中的数据加载到集合中 * B:遍历集合,获取得到每一个键 * C:判断键是否有为"lisi"的,如果有就修改其值为"100" * D:把集合中的数据重新存储到文件中 */public class PropertiesTest {public static void main(String[] args) throws IOException {//把文件中的数据加载到集合中Properties prop = new Properties();Reader r = new FileReader("user.txt");prop.load(r);r.close();//遍历集合,获取得到每一个键Set<String> set = prop.stringPropertyNames();for(String key:set){//判断键是否有为"lisi"的,如果有就修改其值为"100"if(key.equals("lisi")){prop.setProperty(key, "100");break;}}//把集合中的数据重新存储到文件中Writer w = new FileWriter("user.txt");prop.store(w, null);w.close();}}

    运行结果:


    练习2:我有一个猜数字小游戏的程序,请写一个程序实现在测试类中只能用5次,超过5次提示:游戏试玩已结束,请付费。

    创建一个本地文件,写入count=0。


import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.io.Reader;import java.io.Writer;import java.util.Properties;import java.util.Scanner;/* * 分析: * 创建一个本地文件,里面写入count=0,然后读取它,如果次数不大于5,可以继续玩。 * 否则就提示"游戏试玩已结束,请付费。" */public class PropertiesTest2 {public static void main(String[] args) throws IOException {// 读取某个地方的数据,如果次数不大于5,可以继续玩。否则就提示"游戏试玩已结束,请付费。"// 创建一个文件// File file = new File("count.txt");// if(!file.exists()){// file.createNewFile();// }// 把数据加载到集合Properties prop = new Properties();Reader r = new FileReader("count.txt");prop.load(r);r.close();// 我自己的程序,我当然知道里面的键是谁String value = prop.getProperty("count");int number = Integer.parseInt(value);if (number >= 5) {System.out.println("游戏试玩已结束,请付费");System.exit(0);} else {number++;prop.setProperty("count", String.valueOf(number));Writer w = new FileWriter("count.txt");prop.store(w, null);w.close();GuessNumber.start();}}}public class GuessNumber {private GuessNumber() {}public static void start() {// 产生一个随机数int number = (int) (Math.random() * 100) + 1;// 定义一个统计变量int count = 0;while (true) {// 键盘录入一个数据Scanner sc = new Scanner(System.in);System.out.println("请输入数据(1-100):");int guessNumber = sc.nextInt();count++;// 判断if (guessNumber > number) {System.out.println("你猜的数据" + guessNumber + "大了");} else if (guessNumber < number) {System.out.println("你猜的数据" + guessNumber + "小了");} else {System.out.println("恭喜你," + count + "次就猜中了");break;}}}}


    运行结果:


    查看count.txt本地文件


6.8.9 NIO包

    nio包在JDK4出现,提供了IO流的操作效率。但是目前还不是大范围的使用。

    在JDK7.0后,nio包下出现了一些新东西

    Path:与平台无关的路径

    Paths:包含了返回Path的静态方法

        public static Path get(URI uri):根据给定URI来确定文件路径

    Files:操作文件的工具类

        public static long copy(Path source,OutputStream out):复制文件

        public static Path write(Path path,Iterable<? extends CharSequence> lines,Charset cs,OpenOption... options)

import java.util.ArrayList;public class NIODemo {public static void main(String[] args) throws IOException {// 复制文件// public static long copy(Path source,OutputStream out)Files.copy(Paths.get("prop.txt"), new FileOutputStream("Copy.java"));//写文件ArrayList<String> array = new ArrayList<String>();array.add("hello");array.add("world");array.add("java");Files.write(Paths.get("array.txt"),array,Charset.forName("GBK"));}}
    运行结果:




0 0
原创粉丝点击