java IO 学习(二)

文件表示形式的转换:

一、从系统文件变成java中可以使用的文件对象

  File file = new FIle("文件的路径");

二、读取文件系统中文件的原始字节流,要读取字符流,请考虑使用 FileReader (File 转 InputStream

  FileInputStream fis = new FileInputStream(file);

三、创建一个文件输出流,用于写入原始字节流

  FileOutputStream fos = new FileOutputStream(file);

四、将一个输入流其中的数据写入到一个byte数组中(InputStream 转 byte[]

  方法一:

  FileInputStream fis = new FileInputStream(file);

  ByteArrayOutputStream baos = new ByteArrayOutputStream(); 

  byte[] buff = new byte[100]; //buff用于存放循环读取的临时数据 

  int rc = 0; 

  while ((rc = fis.read(buff, 0, 100)) > 0) { 

    baos.write(buff, 0, rc); 

  } 

  byte[] in_b = baos.toByteArray(); // in_b为转换之后的结果 

  方法二:

  FileInputStream fis = new FileInputStream(file);

  byte[] buff = new byte[fis.available()]; 

  fis.read(buff);// read方法返回一个int值,并且把fis读取到的数据保存到buff数组中

  

五、byte[]转换成InputStream

  ByteArrayInputStream bais = new ByteArrayInputStream(byte[] buf);

六、根据byte数组,生成文件

  File file = new File(""); // 新建一个File

  OutputStream output = new FileOutputStream(file);// 转成OutputStream 形式

  BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);// 转成BufferedOutputStream 

  bufferedOutput.write(byt);// 把byte[]写入BufferedOutputStream 

注意有些语句可能会抛出异常,注意流要记得关闭

  

原文地址:https://www.cnblogs.com/qq765065332/p/8744092.html