java 使用字节流读写数据

来源:互联网 发布:海报字体软件 编辑:程序博客网 时间:2024/06/01 23:04
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


原创粉丝点击