首页 > 编程 > Java > 正文

Java基础--流(2)

2019-11-10 17:48:41
字体:
来源:转载
供稿:网友
1.缓冲流​缓冲流要套接在相应的节点流之上,对读写的数据提供了缓冲的功能,提高了读写的效率,同时增加了一些新的方法。​J2SDK提供了四种缓冲流,其常用的构造方法有:​BufferedReader(Reader in)​BufferedReader(Reader int ,int sz)   //sz为自定义缓冲区的大小​BufferedWriter(Writer out)​BufferedWriter(Writer out , int sz)BufferedInoutStream(InputStream in)BufferedInputStream(InputStream in ,int size)BufferedOutputStream(OutputStream out)BufferedOutputStream(OutputStream out,int size)缓冲输入流支持其父类的mark和reset方法,BufferedReader提供了readLine方法用于读取一行字符串(以/r或/n分隔),BufferedWriter提供了newLine用于写入一个行分隔符,对于输出的缓冲流,写出的数据会先在内存缓冲,使用flush方法将会是内存中的数据立刻写入。​举例:
public class TestBufferStream {    public static void main(String args[]) {        try {            FileInputStream fis = new FileInputStream("E://2.txt");            BufferedInputStream bis = new BufferedInputStream(fis);            int c = 0;            System.out.PRintln(bis.read());            System.out.println(bis.read());            bis.mark(100);//标记到第100位            for (int i = 0; i <= 10 && (c = bis.read()) != -1; i++) {                System.out.print((char) c + " ");            }            System.out.println();            bis.reset();            for (int i = 0; i <= 10 && (c = bis.read()) != -1; i++) {                System.out.print((char) c + " ");            }            bis.close();        } catch (IOException e) {            e.printStackTrace();        }    }}结果是:4742a l ; s k j d f ;a l ; s k j d f ;​另一个例子:
public class TestBufferStream {    public static void main(String args[]) {        try {            BufferedWriter bw = new BufferedWriter(new FileWriter("e://2.txt"));            BufferedReader br = new BufferedReader(new FileReader("e://2.txt"));            String s = null;            for (int i = 1; i <= 5; i++) {                s = String.valueOf(Math.random());                bw.write(s);                bw.newLine();            }            bw.flush();            while ((s = br.readLine()) != null) {                System.out.println(s);            }            bw.close();            br.close();        } catch (IOException e) {            e.printStackTrace();        }    }}结果是:0.0248396294456012520.97714146730789510.141005632890089720.92180014804586520.95743394961393472.转换流InputStreamReader和OutputStreanWriter用于字节数据到字符数据之间的转换InputStreamReader需要和InputStream套接,OutputStreamWriter需要和OutputStream套接,转换流在构造时可以指定其编码集合,例如:InputStream isr = new InputStreamReader(System.in,"IS08859_1")​举例:
public class TestTransform1 {    public static void main(String args[]) {        try {            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("e://2.txt"));            osw.write("mircosoftibmsunaoolehp");            System.out.println(osw.getEncoding()); //系统默认是GBk格式            osw.close();            osw = new OutputStreamWriter(new FileOutputStream("e://2.txt", true), "ISO8859_1");//转换成ISO8859_1格式            osw.write("mircosoftibmsunapplehp");            System.out.println(osw.getEncoding());            osw.close();        } catch (IOException e) {            e.printStackTrace();        }    }}结果是:UTF8

ISO8859_1​

文件结果是有两串该字符串,如果去掉true只有一行字符串,该语句表示如果有true时接着原来字符串写,如果没有true'时将原来的擦去在写。​

public class TestTransform1 {    public static void main(String agrs[]) {        InputStreamReader isr = new InputStreamReader(System.in);        BufferedReader br = new BufferedReader(isr);        String s = null;        try {            s = br.readLine();            while (s != null) {                if (s.equalsIgnoreCase("exit")) break;                System.out.println(s.toUpperCase());                s = br.readLine();            }            br.close();        } catch (IOException e) {            e.printStackTrace();        }    }}结果是:输入"nihao",输出NIHAO,当输入exit时退出​​3.数据流​​DataInputStream和DataOutputStream分别继承自InputStream和OutputStream,他属于处理流,需要分别套接在InputStream和OutputStream类型的节点流上。​DataInputStream和DataOutputStream提供了可以存取与机器无关的java原始类型数据(int,double等)的方法。​DataInputStream和DataOutputStream的构造方法为:​DataInputStream(InputStream in)​DataOutputStream(OutputStream out)​举例:​
public class TestDataStream {    public static void main(String args[]) {        ByteArrayOutputStream baos = new ByteArrayOutputStream();        DataOutputStream dos = new DataOutputStream(baos);        try {            dos.writeDouble(Math.random());//8个字节            dos.writeBoolean(true); //1个字节            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());            System.out.println(bais.available());//有多少个字节            DataInputStream dis = new DataInputStream(bais);            System.out.println(dis.readDouble());//先写先读            System.out.println(dis.readBoolean());            dos.close();            dis.close();        } catch (IOException e) {            e.printStackTrace();        }    }}结果是:9     0.9406762018290122    true​4.print流​​PrintWriter和PrintStream都属于输出流,分别针对字符和字节。​PrintWriter和PrintStream提供了重载的Print,Println方法用于多种数据类型的输出。​​PrintWriter和PrintStream的输出操作不会抛出异常,用户通过检测错误状态获取错误信息。PrintWriter和PrintStream有自动的flush功能。​PrintWriter(Writer put)​PrintWriter(Writer out,boolean autoFlush)​PrintWriter(OutputStream out)​​PrintWriter(OutputStream out,boolean autoFlush)PrintStream(OutputStream out)​PrintStream(OutputStream out,boolean autoFlush)​​举例:
public class TestPrintStream1 {    public static void main(String args[]) {        PrintStream ps = null;        try {            FileOutputStream fos = new FileOutputStream("d://A//H.txt");            ps = new PrintStream(fos);        } catch (IOException e) {            e.printStackTrace();        }        if (ps != null) {            System.setOut(ps);//out指向ps        }        int ln = 0;        for (char c = 0; c <= 60000; c++) {            System.out.print(c + " ");            if (ln++ >= 100) {                System.out.println();                ln = 0;            }        }    }}输出结果:是如同前述例子中的一样,有60000个字符的文件。​
public class TestPrintStream1 {    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        String filename = sc.next();        if (filename != null) {            list(filename, System.out);        }    }    public static void list(String f, PrintStream fs) {        try {            BufferedReader br = new BufferedReader(new FileReader(f));            String s = null;            while ((s = br.readLine()) != null) {                fs.println(s);            }            br.close();        } catch (IOException e) {            fs.println("无法读取文件");        }    }}结果:输入文件位置,可以打印出文件的内容​
public class TestPrintStream1 {    public static void main(String[] args) {        String s = null;        BufferedReader br = new BufferedReader(                new InputStreamReader(System.in));        try {            FileWriter fw = new FileWriter("d://A//I.txt", true); //Log4J            PrintWriter log = new PrintWriter(fw);            while ((s = br.readLine()) != null) {                if (s.equalsIgnoreCase("exit")) break;                System.out.println(s.toUpperCase());                log.println("-----");                log.println(s.toUpperCase());                log.flush();            }            log.println("===" + new Date() + "===");            log.flush();            log.close();        } catch (IOException e) {            e.printStackTrace();        }    }}结果是:输入hello输出HELLO,输入ok输出OK,输入exit​文件生成-----HELLO-----OK===Wed Apr 29 16:48:49 GMT+08:00 2015===​5.Object流​直接将Object写入或读出​transient关键字,serializable(序列化)接口(标记型的接口不需要方法,如果想让某个类的对象序列化必须实现该接口),externalizable(extends serializable)接口(提供了两个方法ReadExternal(ObjectInput in),WriteExternal(ObjectOutput out),自己控制序列化过程,直接使用serializable是系统帮我们控制,建议不使用自己控制的)​序列化 (Serialization)将对象的状态信息转换为可以存储或传输的形式的过程。在序列化期间,对象将其当前状态写入到临时或持久性存储区。以后,可以通过从存储区中读取或反序列化对象的状态,重新创建该对象。
public class TestObjectIO {    public static void main(String args[]) throws Exception {        T t = new T();        t.k = 2;        FileOutputStream fos = new FileOutputStream("d://A//G.txt");        ObjectOutputStream oos = new ObjectOutputStream(fos);//专门写Object的流        oos.writeObject(t);        oos.flush();        oos.close();        FileInputStream fis = new FileInputStream("d://A//G.txt");        ObjectInputStream ois = new ObjectInputStream(fis);        T tReaded = (T)ois.readObject();        System.out.println(tReaded.i + " " + tReaded.j + " " + tReaded.d + " " + tReaded.k);    }}
public class T implements Serializable{    int i = 10;    int j = 9;    double d = 2.3;    transient int k = 15;}结果:10 9 2.3 0      并且在相应位置生成一个文件如果没有transient,10 9 2.3 2,transient表示这个成员变量在序列化的时候不予考虑​ 流的综合利用:​
public class 文件字符转换 {    public static void main(String[] args) {        try {            BufferedReader bufReader = new BufferedReader(new InputStreamReader(new FileInputStream(new File("E://1.txt"))));//数据流读取文件            StringBuffer strBuffer = new StringBuffer();            for (String temp = null; (temp = bufReader.readLine()) != null; temp = null) {                if ((temp.indexOf("for") == -1) && (temp.indexOf("if") == -1)) {                    if (temp.indexOf("<") != -1) { //判断当前行是否存在想要替换掉的字符 -1表示存在                        temp = temp.replace("<", "《》");                    }                    if (temp.indexOf(">") != -1) { //判断当前行是否存在想要替换掉的字符 -1表示存在                        temp = temp.replace(">", "》");                    }                }                strBuffer.append(temp);                strBuffer.append(System.getProperty("line.separator"));//行与行之间的分割            }            bufReader.close();            PrintWriter printWriter = new PrintWriter("E://1.txt");//替换后输出的文件位置            printWriter.write(strBuffer.toString().toCharArray());            printWriter.flush();            printWriter.close();        } catch (IOException e) {            e.printStackTrace();        }    }}关于<>的转换
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表