其他分享
首页 > 其他分享> > 018.字节流(21)13/5/2022

018.字节流(21)13/5/2022

作者:互联网

1.FileinputStream的使用

package com.qx.lll;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class StudyInputStream
{
    public static void main(String[] args) throws IOException
    {
        FileInputStream fis = new FileInputStream("aaa.txt");
        int b;
        while ((b = fis.read())!= -1)
        {
            System.out.println((char) b);
        }
        fis.close();
    }
}

2.FileoutStream的使用

package com.qx.lll;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class StudyOutStream
{
    public static void main(String[] args) throws IOException
    {
        FileOutputStream fos = new FileOutputStream("bbb.txt");
        fos.write(97);
        fos.write(98);
        fos.write(99);
        fos.write(78);
        fos.close();

    }
}

3.拷贝文件效率最低的方法

package com.qx.lll;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Picture
{
    public static void main(String[] args) throws IOException
    {
        FileInputStream fis = new FileInputStream("123.jpg");
        FileOutputStream fos = new FileOutputStream("321.jpg");
        int receive;
        while ((receive = fis.read())!= -1)
        {
            fos.write(receive);
        }
        fis.close();
        fos.close();

    }
}

(1)针对上面在改进

(由于java虚拟机分配内存的问题,这种方法不推荐)

package com.qx.lll;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Media
{
    public static void main(String[] args) throws IOException
    {
        FileInputStream fis = new FileInputStream("1234.mp3");
        FileOutputStream fos = new FileOutputStream("4321.mp3");
        byte[] bytes = new byte[fis.available()];//可以获取与文件关联的字节数
        fis.read(bytes);
        fos.write(bytes);
        fis.close();
        fos.close();
    }
}

(2)在改进

package com.qx.lll;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class MediaTwo
{
    public static void main(String[] args) throws IOException
    {
        FileInputStream in = new FileInputStream("789.mp3");
        FileOutputStream out = new FileOutputStream("987.mp3");
        int len;
        byte[] bytes = new byte[1024 * 8];
        while ((len = in.read(bytes))!= -1)
        {
            System.out.println(len);//打印每次读取多少个字节
            out.write(bytes,0,len);//write 中参数的意思:将指定字节数组中从偏移量off开始的len个字节写入此文件输出流
        }
        in.close();
        out.close();
    }
}

 

标签:13,java,2022,fos,FileOutputStream,io,FileInputStream,018,import
来源: https://www.cnblogs.com/LLL0617/p/16265272.html