InputStream抽象类是所有类字节输入流的超类
InputStream常用的子类
1.FildInputStream:文件输入流2.BufferedInputStream:缓冲字节输入流3.ObjectInputStream:对象字节输入流
InputStream代码案例
// 演示读取文件@Testpublic void readFile01(){String filePath = "e:\\news1.txt";int readDate = 0;FileInputStream fileInputStream = null;try {// 创建 FileInputStream 对象,用于读取文件fileInputStream = new FileInputStream(filePath);// 从该输入流读取一个字节的数据,如果没有输入可用,此方法将阻止// 如果返回-1,表示读取完毕while ((readDate = fileInputStream.read()) != -1){System.out.print((char) readDate); // 转成char显示}} catch (IOException e) {e.printStackTrace();}finally {// 关闭文件流释放资源try {fileInputStream.close();} catch (IOException e) {e.printStackTrace();}}}/** 使用read(byte[] b)读取文件,提高效率* */@Testpublic void readFile02(){String filePath = "e:\\news1.txt";byte[] buf = new byte[8]; // 一次读取8个字节int readLen = 0;FileInputStream fileInputStream = null;try {// 创建 FileInputStream 对象,用于读取文件fileInputStream = new FileInputStream(filePath);// 从该输入流读取一个字节的数据,如果没有输入可用,此方法将阻止// 如果返回-1,表示读取完毕// 如果读取正常,返回实际读取的字节数while ((readLen = fileInputStream.read(buf)) != -1){System.out.print(new String(buf, 0, readLen)); // 转成char显示}} catch (IOException e) {e.printStackTrace();}finally {// 关闭文件流释放资源try {fileInputStream.close();} catch (IOException e) {e.printStackTrace();}}}
OutputStream代码案例
// 演示使用FileOutputStream将数据写到文件中,如果文件不存在,则创建该文件@Testpublic void writeFile(){// 创建 FileOutputStream对象String filePath = "e:\\news1.txt";FileOutputStream fileOutputStream = null;try {/*1.fileOutputStream = new FileOutputStream(filePath); 创建方式,当写入内容时,会覆盖原来的文本内容2.fileOutputStream = new FileOutputStream(filePath,true); 创建方式,当写入内容时,是追加到文本内容后面*/fileOutputStream = new FileOutputStream(filePath,true);// 写入一个字节// fileOutputStream.write('H');// 写入一个字符串String str = "hello,www";// str.getBytes() 可以把字符串转成字节数组// fileOutputStream.write(str.getBytes());// write(str.getBytes(),0,int len) 将len字节从位于偏移量 off的指定字节数组fileOutputStream.write(str.getBytes(),0,str.length());} catch (IOException e) {e.printStackTrace();}finally {try {fileOutputStream.close();} catch (IOException e) {e.printStackTrace();}}}
拷贝文件代码
public static void main(String[] args) {String srcPath = "e:\\1.jpg";String destPath = "e:\\2.jpg";FileInputStream fileInputStream = null;FileOutputStream fileOutputStream = null;try {fileInputStream = new FileInputStream(srcPath);fileOutputStream = new FileOutputStream(destPath);// 定义一个字节数组,提高读取效果byte[] buf = new byte[1024];int readLen = 0;while ((readLen = fileInputStream.read(buf)) != -1) {// 读取到后,就写入到文件,通过fileOutputStream// 即,是一边写一边读fileOutputStream.write(buf,0,readLen); // 一定要使用这个方法}System.out.println("拷贝成功");} catch (IOException e) {e.printStackTrace();} finally {try {// 关闭输入流和输出流,释放资源if (fileInputStream != null) {fileInputStream.close();}if (fileOutputStream != null) {fileOutputStream.close();}} catch (IOException e) {e.printStackTrace();}}}
