当前位置: 代码迷 >> 综合 >> Java基础 -> IO流(FileInputStream, FileOutputStream)字节流,节点流
  详细解决方案

Java基础 -> IO流(FileInputStream, FileOutputStream)字节流,节点流

热度:85   发布时间:2023-12-16 10:10:09.0

方式一:直接输入

 /*** 使用字节流复制图片:方式一:直接输入* @throws IOException*/@Testpublic void test2() throws IOException {
    //输入流:文件输入到内存缓存FileInputStream fileInputStream = new FileInputStream("我是存在的图.png");//输出流:内存缓存输出到文件FileOutputStream fileOutputStream = new FileOutputStream("我是新建的空的图.png");int len = 0;//读到-1就表明没有可读的了,已经读完了while ((len = fileInputStream.read()) != -1) {
    //读到的全部输入进新建的图fileOutputStream.write(len);}//关闭流,释放缓冲 类似方法.flush()fileInputStream.close();fileOutputStream.close();}

方式一:直接输入(try-catch型)

    @Testpublic void test2()  {
    FileInputStream fileInputStream = null;FileOutputStream fileOutputStream = null;try {
    fileInputStream = new FileInputStream("我是存在的图.png");fileOutputStream = new FileOutputStream("我是新建的空的图.png");int len = 0;while ((len = fileInputStream.read()) != -1) {
    fileOutputStream.write(len);}} catch (IOException e) {
    e.printStackTrace();} finally {
    if (fileInputStream != null && fileOutputStream != null){
    try {
    fileInputStream.close();fileOutputStream.close();} catch (IOException e) {
    e.printStackTrace();}}}}

方式二:存入byte(try-catch型)

  /*** 方式二:存入byte* 什么时候用字节流(input,output):图片,MP3等* 什么时候用字符流(reader,writer) :txt,汉子等* 下面用字节流将存在的一个图片1复制进新建的图片2* 先将1输入进内存,在内存输出到2*/@Testpublic void test1(){
    FileInputStream fileInputStream = null;ArrayList arrayList = new ArrayList();try {
    File file = new File("QQ截图20200922195443.png");fileInputStream = new FileInputStream(file);int read;while ((read = fileInputStream.read()) != -1){
    //输入进一个list,list后面输出到另一个filearrayList.add(read);}} catch (IOException e) {
    e.printStackTrace();} finally {
    if (fileInputStream != null){
    try {
    fileInputStream.close();} catch (IOException e) {
    e.printStackTrace();}}}FileOutputStream fileOutputStream = null;try {
    File file = new File("fuzhi.png");fileOutputStream = new FileOutputStream(file);//将list中的数据转化稳数组,类型为objectObject[] array = arrayList.toArray();int i=0;byte[] bytes = new byte[array.length];while (i < array.length){
    for (Object obj : array){
    //Object转化为string,转化为int,强制为bytebytes[i] = (byte)Integer.parseInt(String.valueOf(obj));i++;}}fileOutputStream.write(bytes);} catch (IOException e) {
    e.printStackTrace();} finally {
    if (fileOutputStream != null){
    try {
    fileOutputStream.close();} catch (IOException e) {
    e.printStackTrace();}}}}
  相关解决方案