IO:在设备和设备之间的一种数据传输!
IO流的分类:
按流的方向分:
输入流: 读取文件 (e:\\a.txt):从硬盘上文件读取出来后输出这个文件的内容
输出流: 写文件:将e:\\a.txt 内容读出来--->写到f盘下
按数据的类型划分:
字节流
字节输入流:InputStream :读取字节
字节输出流:OutputStream :写字节
字符流
字符输入流:Reader :读字符
字符输出流:Writer :写字符
public static void main(String[]args) throws IOException {
//创建一个字节输出流对象
FileOutputStream fos=new FileOutputStream("a.txt");
//写入数据
fos.write("hello".getBytes());
//关闭资源
fos.close();
}
字节输出流写数据的方法
public void write(int b):一次写一个字节
public void write(byte[] b) :一次写一个字节数组
public void write(byte[] b, int off,int len):一次写一部分字节数组
public static void main(String[]args) throws IOException {
//创建字节输出流对象
FileOutputStream fos=new FileOutputStream("b.txt");
//fos.write(97);
//fos.write(98);
byte[]b= {97,98,99,100,101};
fos.write(b);
fos.close();
}
输出文本文件,给文本文件中添加一些数据
public FileOutputStream(File file, boolean append)
指定为true,末尾追加数据
public static void main(String[]args) throws IOException {
//创建输出流对象
FileOutputStream fos=new FileOutputStream("c.txt",true);
fos.write(98);
for(int x=0;x<10;x++) {
fos.write("hello".getBytes());
fos.write("\r\n".getBytes());
}
fos.close();
}
InputStream抽象类:字节输入流
FileInputStream
构造方法:
public FileInputStream(String name)
读数据方式:
public abstract int read():一次读取一个字节
public int read(byte[] b):一次读取一个字节数组 (读取实际的字节数)
public static void main(String[]args) throws IOException {
//创建字节文件输入流对象
FileInputStream fis=new FileInputStream("a.txt");
int by=0;
while((by=fis.read())!=-1) {
System.out.println((char)by);
}
}