定义:
- 可以从其中读入一个字节系列的对象称为输入流
- 可以向其中写入一个字节系列的对象称为输出流
- 字节系列的来源地和目的地可以是文件,而且通常是文件,也可以是网络连接和内存块
- 抽象类Inputtream和OutputStream构成的输入/输出(I / O)类层次结构的基础,基于一个字节byte进行操作
- 抽象类读者和作家中继承出来专门处理的Unicode字符的单独的类层次结构,这些类主要拥有读入和写出操作都是基于两个字节的字符
读取字节:
- InputStream类中的抽象方法:abstract int read(),这个方法读入一个字节并返回读入字节,或者在遇到输入源结尾时,返回-1
- 子类必须覆盖方法abstract int read(),FileInputStream类中,这个方法将从某个文件中读取字节
常用读取字节方法:
- int read(byte [] b),从数据流读入一个字节数组,返回当前读入的字节数,返回-1
- void close(),关闭数据流,这个方法可以抛出IOException异常
- long skip(long n),返回实际跳过的字节数(如果碰到输入流的结尾,则可能小于n)
/** * * @param file * 传入文件 * @return 文件内容 */ public static String inputByete(File file) { try { InputStream input = null; try { if (file.exists() && file.isFile()) { input = new FileInputStream(file);//通过打开一个到实际文件的连接来创建一个 FileInputStream byte[] b = new byte[(int) file.length()]; input.read(b);//从此输入流中将最多 file.length 个字节的数据读入一个 byte 数组中。在某些输入可用之前,此方法将阻塞。 return new String(b); } else { throw new NullPointerException(); } } finally { input.close();//关闭数据流 } } catch (FileNotFoundException | NullPointerException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
- OutputStream中抽象方法:abstract void write(int b),向指定文件输出字节
- 子类FileOutputStream类,写(byte [] int),输出指定字节数组
常用输入字节方法
- void write(byte [] b),将指定字节数组输入到指定文件
- void close(),冲刷并关闭输入流程
- void close(),冲刷输出流,也就是将所有缓冲的数据发送到指定位置
/** * 将一个字符串写入指定文件 * * @param file写入文件文件 * @param str写入字符串 * @throws FileNotFoundException */ public static void outputByte(File file, String str) { try { if (file.exists() && file.isFile()) { // 判定文件是否存在,或是不是目录 OutputStream output = null; try { output = new FileOutputStream(file);//创建一个向指定 File 对象表示的文件中写入数据的文件输出流 output.write(str.getBytes()); // 将 b.length 个字节从指定 byte 数组写入此文件输出流中,getBytes(),将字符串转换为字符数组 } finally { output.close();//关闭输出流 } } else { throw new FileNotFoundException(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
读取字符:
- Reader类中的抽象方法:abstract int read() ,这个方法读入一个字符并返回读入的字符对应的Unicode,或者在遇到输入源结尾时,返回-1
- 子类必须覆盖方法abstract int read(),FileReader类中,这个方法将从某个文件中读取字符
/**
* 字符输入流的演示,未判定文件
*/
try {
FileReader input = new FileReader(file); // 用来读取字符文件的便捷类。此类的构造方法假定默认字符编码和默认字节缓冲区大小都是适当的
try {
@SuppressWarnings("resource")
BufferedReader cache = new BufferedReader(input); // 从字符输入流读取文本,缓冲字符,以便字符,数组和行的高效读取
String inputTxt = "";
while ((inputTxt = cache.readLine()) != null) { // 将读取的字符赋值给inputTxt
System.out.println(inputTxt);
}
} finally {
input.close();// 关闭输入流
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
输入字符:
- Writer中抽象方法:abstract void write(int b),向指定文件输出字符
- 子类FileWriter类,write(char [] str),输出指定字符数组,write(String str)输出指定的字符串
/ ** *字符输出流 * / String source =“learn how to write to file”; FileWriter output = null; try{ try{ output = new FileWriter(file); //用来写入字符文件的便捷类。 output.write(source); } finally { output.close(); //关闭输出流 } } catch(IOException e){ e.printStackTrace(); }