JAVA学习-----IO数据流

JAVA学习-----IO数据流

一.输入

1.创建源

    File src=new File("test.txt");

2.选择流

InputStream is=null;
    try {
        is=new FileInputStream(src);

3.操作(读取)
未分段:

int temp;
        while((temp=is.read())!=-1) {
            System.out.println((char)temp);
        }

分段:

byte[] flush=new byte[1024];//缓冲容器
        int len=-1;//接收长度
        while((len=is.read(flush))!=-1) {
            //字符数组->字符串(解码)
            String str=new String(flush,0,len);
            System.out.println(str);
        }

4.释放资源(finally)

    try {
            if(null!=is) {
            is.close();
            }

其他,设置相应try和catch。


二.输出

过程与输入类似。
1.创建源

        File dest=new File("dest.txt");

2.选择流

OutputStream os=null;
    try {
        os=new FileOutputStream(dest,false);

3.操作(写出内容)

String msg="IO is not easy\r\n";
        byte[] datas=msg.getBytes();
        os.write(datas, 0, datas.length);

4.释放资源(finally)

try {
            if(null!=os) {
            os.close();
            }

三.复制

将输入和输出结合即可,最好封装起来。

public static void copy(String srcPath,String destPath) 

注意:释放资源,分别关闭,先打开的后关闭。

猜你喜欢

转载自www.cnblogs.com/CGJ-Coco/p/9724457.html