FileInputStream
FileInputStream从文件系统中的某个文件中获得输入字节。构造方法:1.FileInputStream(File file)通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的File对象file指定。2.FileInputStream(String name)通过打开一个到实际文件的连接来创建一个FileInputStream,该文件通过文件系统中的路径名name指定。成员方法:1.read() 从此输入流中读取一个数据字节,如果没有输入该方法将会阻塞。2.read(byte[] b) 从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。3.read(byte[] b, int off, int len) 从此输入流中将最多len个字节的数据读入一个byte数组中。4.close() 关闭此文件输入流并释放与此流有关的所有系统资源。
//二进制文件读取案例public static void main(String[] args) { String filePath = "C:\\Users\\ms674\\Desktop\\File\\img1.png"; //FileInputStream从文件系统中的某个文件中获得输入字节。 FileInputStream fis = null; try { //创建FileInputStream对象,用于读取本地文件 fis = new FileInputStream(new File(filePath)); int len; byte[] bs = new byte[1024]; //如果返回-1表示读取完毕,如果读取正常返回实际读取的字节数 while ((len = fis.read(bs)) != -1) { System.out.println(new String(bs, 0, len)); } } catch (IOException e) { e.printStackTrace(); } finally { if (fis != null) { try { fis.close();//关闭本地输入字节流 } catch (IOException e) { e.printStackTrace(); } } }}
FileOutputStream
文件输出流是用于将数据写入File或FileDescriptor 的输出流。构造方法:1.FileOutputStream(File file) 创建一个向指定 File对象表示的文件中写入数据的文件输出流。2.FileOutputStream(File file, boolean append) 创建一个向指定File对象表示的文件中写入数据的文件输出流。成员方法:1.close() 关闭此文件输出流并释放与此流有关的所有系统资源。2.write(byte[] b) 将b.length个字节从指定 byte 数组写入此文件输出流中。3.write(byte[] b, int off, int len) 将指定 byte 数组中从偏移量off开始的len个字节写入此文件输出流。4.write(int b) 将指定字节写入此文件输出流。
//二进制流写文件案例public static void main(String[] args) { //创建FilePutStream对象 String filePath = "C:\\Users\\ms674\\Desktop\\File\\file2.txt"; FileOutputStream fos = null; try { //得到FileOutputStream对象,如果文件不存在就创建文件 //默认覆盖形式写入 fos = new FileOutputStream(new File(filePath),true); //写入数据 fos.write("FileOutPutStream...".getBytes()); } catch (IOException e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close();//关闭FileOutPutStream } catch (IOException e) { e.printStackTrace(); } } }}
二进制文件拷贝案例
public static void main(String[] args) { String sourcePath = "C:\\Users\\ms674\\Desktop\\File\\img1.png"; String copyPath = "C:\\Users\\ms674\\Desktop\\File\\DDD\\copy-img1.png"; FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(sourcePath); fos = new FileOutputStream(copyPath); int len; byte[] bs = new byte[1024]; while ((len = fis.read(bs)) != -1) { fos.write(bs,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } }}