java 使用字节流读写数据

1   字节流读取
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ReadByteStream {
 public static void main(String[] args) {
  //使用相对路径
  try {
   @SuppressWarnings("resource")
   FileInputStream fileInputStream = new FileInputStream("text.txt");
       //创建字节数组中
   byte input[] = new byte[31];
   //将读取到的数据 存放到数组中去
   fileInputStream.read(input); //读取到字节数组中
   //读取到的数据转化为字符串
   String inputString = new String(input,"UTF-8");//指定当前解码方试为"UTF-8"
      System.out.println(inputString);
  } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
  
 }

}

案例 结果:

第一行
第二行
第三行


2  字节流 的拷贝:


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/*
 * 文件的 拷贝
 */
public class CopyByByteStream {

 @SuppressWarnings("resource")
 public static void main(String[] args) throws FileNotFoundException {
  // TODO Auto-generated method stub
     try {
  @SuppressWarnings("resource")
  FileInputStream fileInputStream = new FileInputStream("1.jpg");
  @SuppressWarnings("unused")
  FileOutputStream fileOutputStream =new FileOutputStream("1new.jpg");
  byte input[] = new byte[50];
  
  //将文件写入数组   fileInputStream.read(input)放回的是数值  如不为-1 说明 还有数据
  while(fileInputStream.read(input)!=-1)
  {
   //将文件写出到新的数组中
   fileOutputStream.write(input);
  }
  fileInputStream.close();
  fileOutputStream.close();
  System.out.println("done");
     } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
    
 }

}

案例 结果:

done


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值