行业资讯
【南京开发培训】Java开发的输出和输入流(二)
2019-11-01

 在java的语言中所以的所有数据都是使用流读写的。那么什么是流呢?

 


 

      下面就对常用子类使用进行代码演示说明:

1、FileInputStream 和FileOutputStream进行二进制读写

这里的文件后缀是txt,但该文件却是一个二进制文件,并不能直接查看。

package ustc.maxiaolun.io;

import java.io.*;

public class Test1 {

    public static void main(String[] args) throws IOException {

        testRead();      

testWrite();

    }

    public void testRead() throws IOException {

        FileInputStream fileInputStream = new FileInputStream(new File("").getAbsolutePath()+"/io/test2.txt");

        int c;

        // 读取写入的二进制文件,输出字节数组

        while ((c = fileInputStream.read()) != -1) {

            System.out.print(c);

        }

        fileInputStream.close();

    }

   public void testWrite() throws IOException {

        byte[] bytes = {12,21,34,11,21};

        FileOutputStream fileOutputStream = new FileOutputStream(new File("").getAbsolutePath()+"/io/test1.txt");

        // 写入二进制文件,直接打开会出现乱码

        fileOutputStream.write(bytes);

        fileOutputStream.close();

    }

}

 

2、FileReader和FileWriter 文本文件的写入和读取

write()方法和append()方法并不是像方法名那样,一个是覆盖内容,一个是追加内容,append() 内部也是 write() 方法实现的,也非说区别,也就是 append() 方法可以直接写 null,而 write() 方法需要把 null 当成一个字符串写入,所以两者并无本质的区别。

需要注意的是这里并没有指定文件编码,可能会出现乱码的问题。

package ustc.maxiaolun.io;

import java.io.*;

 

public class Test2 {

    public static void main(String[] args) throws IOException {

        testAppend();      

testOverride();

        testString();      

testChar();

    }

    public void testAppend()  {

        FileWriter fileWriter = new FileWriter(new File("").getAbsolutePath()+"/io/test1.txt");

        fileWriter.write("Hello,world!\n欢迎来到 java 流世界\n");

        fileWriter.write("不会覆盖文件原本的内容\n");

        fileWriter.append("并不是追加一行内容,不要被方法名迷惑\n");

        fileWriter.append(null);

        fileWriter.flush();

        System.out.println("文件的默认编码为" + fileWriter.getEncoding());

        fileWriter.close();

    }

    public void testOverride ()  {

        FileWriter fileWriter = new FileWriter(new File("").getAbsolutePath()+"/io/test2.txt", false); // 关闭追加模式,变为覆盖模式

        fileWriter.write("Hello,world!欢迎来到 java 流世界\n");

        fileWriter.write("我来覆盖文件原本的内容");

        fileWriter.append("我是下一行");

        fileWriter.flush();

        System.out.println("文件的默认编码为" + fileWriter.getEncoding());

        fileWriter.close();

    }

    public void testString() {

        FileReader fileReader = new FileReader(new File("").getAbsolutePath()+"/io/test3.txt");

        BufferedReader bufferedReader = new BufferedReader(fileReader);

        String str;

        while ((str = bufferedReader.readLine()) != null) {

            System.out.println(str);

        }

        fileReader.close();

        bufferedReader.close();

    }

    public void testChar()  {

        FileReader fileReader = new FileReader(new File("").getAbsolutePath()+"/io/test4.txt");

        int c;

        while ((c = fileReader.read()) != -1) {

            System.out.print((char) c);

        }

fileReader.close();

    }

}

 

3、InputStreamReader 和 OutputStreamWriter 可以对字节流到字符流的转换, 可以指定文件的编码,使用 Buffer 相关的类来读取文件的每一行

package ustc.maxiaolun.io;

import java.io.*;

public class Test3 {

    public static void main(String[] args) throws IOException {

        testWrite();      

testRead();

    }

   public void testWrite()  {

        FileOutputStream fileOutputStream = new FileOutputStream(new File("").getAbsolutePath()+"/io/test1.txt");

        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "GBK"); // 使用 GBK 编码文件

        outputStreamWriter.write("Hello,world!\n欢迎来到 java 流世界\n");

        outputStreamWriter.append("另外一行内容");

        outputStreamWriter.flush();

        System.out.println("文件的编码为" + outputStreamWriter.getEncoding());

        outputStreamWriter.close();

        fileOutputStream.close();

    }

    public void testRead()  {

        FileInputStream fileInputStream = new FileInputStream(new File("").getAbsolutePath()+"/io/test1.txt");

        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "GBK"); // 使用 GBK 解码文件

        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        String str;

        while ((str = bufferedReader.readLine()) != null) {

            System.out.println(str);

        }

        bufferedReader.close();

        inputStreamReader.close();

    }

}

 

  4、BufferedInputStream 和 BufferedOutputStream 提供缓冲复制大数据文件

文件的复制实质还是文件的读写。缓冲流是处理流,是对节点流的装饰。

package ustc.maxiaolun.io;

import java.io.*;

public class Test4 {

    public static void main(String[] args) throws IOException {

        test01();      

//test02();   

//test03();   

//test04();   

    }

  public void  test01()  {

        // 输入和输出都使用缓冲流

        FileInputStream in = new FileInputStream("c:\\大数据时代.mp4");

        BufferedInputStream inBuffer = new BufferedInputStream(in);

        FileOutputStream out = new FileOutputStream("d:\\大数据时代.mp4");

        BufferedOutputStream outBuffer = new BufferedOutputStream(out);

        int len = 0;

        byte[] bs = new byte[1024];

        long begin = System.currentTimeMillis();

        while ((len = inBuffer.read(bs)) != -1) {

            outBuffer.write(bs, 0, len);

        }

        System.out.println("复制文件所需的时间:" + (System.currentTimeMillis() - begin)); // 平均时间约 200 多毫秒

        inBuffer.close();

        in.close();

        outBuffer.close();

        out.close();

    }

 

    public void  test02()  {

        // 只有输入使用缓冲流

        FileInputStream in = new FileInputStream("c:\\大数据时代.mp4");

        BufferedInputStream inBuffer = new BufferedInputStream(in);

        FileOutputStream out = new FileOutputStream("d:\\大数据时代.mp4");

        int len = 0;

        byte[] bs = new byte[1024];

        long begin = System.currentTimeMillis();

        while ((len = inBuffer.read(bs)) != -1) {

            out.write(bs, 0, len);

        }

        System.out.println("复制文件所需时间:" + (System.currentTimeMillis() - begin)); // 平均时间约 500 多毫秒

        inBuffer.close();

        in.close();

        out.close();

    }

    public void test03() {

        // 输入和输出都不使用缓冲流

        FileInputStream in = new FileInputStream("c:\\大数据时代.mp4");

        FileOutputStream out = new FileOutputStream("d:\\大数据时代.mp4");

        int len = 0;

        byte[] bs = new byte[1024];

        long begin = System.currentTimeMillis();

        while ((len = in.read(bs)) != -1) {

            out.write(bs, 0, len);

        }

        System.out.println("复制文件所需时间:" + (System.currentTimeMillis() - begin)); // 平均时间 700 多毫秒

        in.close();

        out.close();

    }

    public void test04()  {

        // 不使用缓冲

        FileInputStream in = new FileInputStream("c:\\大数据时代.mp4");

        FileOutputStream out = new FileOutputStream("d:\\大数据时代.mp4");

        int len = 0;

        long begin = System.currentTimeMillis();

        while ((len = in.read()) != -1) {

            out.write(len);

        }

        System.out.println("复制文件所需时间:" + (System.currentTimeMillis() - begin)); // 平均时间约 160000 毫秒,约 2 分多钟

        in.close();

        out.close();

    }

}

 

5、BufferedReader 读取控制台的输入

package ustc.maxiaolun.io;

import java.io.*;

public class Test5 {

    public static void main(String[] args) throws IOException {

        test01();      

//test02();   

//test03();     

    }

    public static void test01() {

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

        System.out.println("请输入一个字符");

        char c;

        c = (char) bufferedReader.read();

        System.out.println("你输入的字符为"+c);

    }

    public static void test02() {

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

        System.out.println("请输入一个字符,按 q 键结束");

        char c;

        do {

            c = (char) bufferedReader.read();

            System.out.println("你输入的字符为"+c);

        } while (c != 'q');

    }

    public static void test03() {

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

        System.out.println("请输入一行字符");

        String str = bufferedReader.readLine();

        System.out.println("你输入的字符为" + str);

    }

}

至于控制台的输出,我们其实一直都在使用呢,System.out.println() out 其实是 PrintStream 类对象的引用,PrintStream 类中当然也有 write() 方法,但是我们更常用 print() 方法和 println() 方法,因为这两个方法可以输出的内容种类更多,比如一个打印一个对象,实际调用的对象的 toString() 方法。

 

6、DataInputStream和DataOutputStream与机器无关方式读写基本Java数据类型

注意:要用DataInputStream 读取一个文件,这个文件必须是由DataOutputStream 写出的,否则会出现EOFException,因为DataOutputStream 在写出的时候会做一些特殊标记,只有DataInputStream 才能成功的读取。

package ustc.maxiaolun.io;

import java.io.*;

public class DataStreamDemo

{

public static void main(String[] args)

{

try

{

DataOutputStream out=new DataOutputStream(new FileOutputStream("c:\\test.txt"));

double[] prices={18.99,9.22,14.22,5.22,4.21};

int[] units={10,10,20,39,40};

String[] descs={"bike","book","boat","boot","bus"};

for(int i=0;i<prices.length;i++)

{

try

{

out.writeDouble(prices[i]);

out.writeChar('\t');

out.writeInt(units[i]);

out.writeChar('\t');

out.writeChars(descs[i]);

out.writeChar('\n');

}

catch (IOException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

 

}

try

{

out.close();

}

catch (IOException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

}

catch (FileNotFoundException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

 

try

{

DataInputStream in=new DataInputStream(new FileInputStream("c:\\test.txt"));

double prices;

int num;

StringBuffer name;

char chr;

int len;

 

try

{

while(true)

{

len=5;

name=new StringBuffer();

prices=in.readDouble();

in.readChar();

num=in.readInt();

in.readChar();

while((chr=in.readChar())!='\n')

{

name.append(chr);

}

//double类型转String类型以及加入空格对齐的方法

System.out.println("产品名称:"+name+"\t价格:"+prices+getBlanks(len-Double.toString(prices).length())+"\t数量:"+num);

}

}

catch (IOException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

}

catch (FileNotFoundException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

}

//加入空格进行对齐操作

public static String getBlanks(int n)

{

String str="";

while(n>0)

{

str+=" ";

n--;

}

return str;

}

}

输出结果如下:

 

 

7、ObjectInputStream和ObjectOutputStream 序列化对象

序列化是指把Java对象保存为二进制字节码的过程,Java反序列化是指把二进制码重新转换成Java对象的过程

序列化是一种轻量级的持久化,对象都是存活在内存中的,当JVM运行结束,对象便不存在了

package ustc.maxiaolun.io;

import java.io.*;

public class Pet implements Serializable{

private static final long serialVersionUID = 1L;

private String name;

private int health;

private int love;

 

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getHealth() {

return health;

}

public void setHealth(int health) {

this.health = health;

}

public int getLove() {

return love;

}

public void setLove(int love) {

this.love = love;

}

}

package ustc.maxiaolun.io;

import java.io.*;

public class TestSerializable {

public static void main(String[] args) throws Exception{

Pet pet=new Pet();

pet.setName("猫咪");

pet.setLove(1);

pet.setHealth(1);

OutputStream ops = null;

ObjectOutputStream oos = null;

 

try {

ops = new FileOutputStream("c:/pet.dat");

oos = new ObjectOutputStream(ops);

oos.writeObject(pet);

} catch (FileNotFoundException e) {

e.printStackTrace();

}catch (IOException e) {

e.printStackTrace();

}finally {

try {

oos.close();

ops.close();

} catch (IOException e) {

e.printStackTrace();

}

}

 

InputStream is = new FileInputStream("c:/pet.dat");

ObjectInputStream ois = new ObjectInputStream(is);

 

Pet p= (Pet)ois.readObject();

System.out.println("------name---->"+p.getName());

ois.close();

is.close();

}

}

 

(未完待续……)

 

 

下面给大家分享一下正厚软件对于软件测试的进阶课程大纲:

 

    2019正厚软件软件测试课程要点及大纲

 

2019正厚软件IT职能培训网报方式

 

如果需要详细了解试听或培训课程费用可留下 姓名+联系方式(手机号或微信号),我们会在第一时间为您解答服务!

 

软件测试零基础班

软件测试周末精品班

java开发班

ISTQB考试班

 

更多资讯尽在官方网站

www.njzhenghou.com

咨询热线
预约试听:025-86665061
官方公众号:ZhenghouSoft
技术热线:025-86665061
联系地址
南京总部:南京市鼓楼区湖南路16号5楼
重庆中心:重庆市渝中区投资大厦6楼
武汉中心:江夏区光谷智慧园16栋
微信公众号
联系我们
咨询热线:025-86665061
友情链接
Copyright © 2018 南京正厚软件 苏ICP备17057415号 网站地图 XML地图