IO流
-
字符流
- 只能操作普通文本文件(.txt、.java、.cpp等)
-
字节流
- 能操作一切文件,包括字符流
-
java中的四大流
- 字符输入流:
- 共同父类:Reader—FileReader,BufferedReader
- 功能:读取一个字符、字符数组
- 字符输出流
- 共同父类:Writer—FileWriter,BufferedWriter
- 功能:写一个字符、字符数组、字符串
- 字节输入流
- 共同父类:InputStream—FileInputStream、BufferedInputStream
- 功能:读取一个字节、字节数组
- 字节输出流
- 共同父类:OutputStream—FileOutputStream、BufferedOutputStream
- 功能:写一个字节、字节数组
- 规律:
- 输入流方法名一定叫做—read
- 输出流方法名一定叫做—write
- 流命名—功能+父类名字
- 字符输入流:
字节流
此抽象类中的方法
public void close(); //关闭流
public void flush(); //刷新流
//与写数据有关的方法
public void write(int ASCCI); //写一个字节
public void write(byte [] bt); //写一个字节数组
public void write(byte [] bt,int startIndsx,int length); //写字节数组的一部分
子类:FileOutputStram文件输出流
//两个构造方法,输出文件可是一个文件对象,也可是一个文件的名字
public FileOutputStream(String filename,bool flag); //flag为true时表示可续写,默认为不续写
public FileOutputStream(File file,bool flag); //文件可是一个文件对象,也可是一个文件的名字
FileOutputStram中输出换行
- windows:\r\n
- linux:\n
- Max:\r
此抽象类的构造方法
public int read(); //读取一个字节,读出的时ASCCI码值
public int read(byte [] bt); //读取一个字节数组,返回值为读取的字节数
子类:FileInputStream文件读取流
//两个构造方法,读取文件可是一个文件对象,也可是一个文件的名字
public FileInputStream(File file)
public FileInputStream(String name)
例:读取操作
byte [] bs = new byte[4]; //保存读入的数据
int len=0; //获取每次读入数据的长度
while((len = file.read(bs))!=-1){ //循环读入
//每次输出len个字符,防止出现输出出错
system.out.print(new String(bs,0,len)) //转换为String字符串输出
}
源文件:读取用的,new FileInputStream(“源文件”)
目标文件:写入用的,new FileOutputStream(“目标文件”)
FileInputStream fis = new FileInputStream("源文件")
FileOutputStream fos = new FileOutputStream("目标文件")
byte [] bs = new byte[1024]; //保存读入的数据
int len=0; //获取每次读入数据的长度
while((len = fis.read(bs))!=-1){ //判读是否有读入
fos.wrtie(bs,0,len) //输出
}
BufferedInputStream:方法与FileInputStream一致
BufferedInputStream bos = new BufferedInputStream(FileInputStream fis);
BufferedInputStream bos = new BufferedInputStream(new FileInputStream("源文件名"));
BufferedOutputStream(与上例一致)
单级文件夹:里面只有文件没有文件夹
public static void main(String[] args) throws IOException {
//创建源文件与目标文件对象
File filesrc = new File("目标文件");
File fileobj = new File("目标文件");
//判断目标文件是否存在
if(!fileobj.exists()) {
fileobj.mkdir();
}
//获取需要复制的文件对象数组
File [] filecoyred = filesrc.listFiles();
//复制文件
for (File file : filecoyred) {
//拼接复制完成后文件的地址和文件名
File obj = new File(fileobj, file.getName());
//创建被复制文件与复制文件对象
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(obj));
byte [] bt = new byte[1024];
int len = 0;
//边读取边复制
while((len = bis.read(bt))!=-1) {
bos.write(bt,0,len);
}
System.out.println(file.getName() + "文件复制成功");
//关闭资源
bos.close();
bis.close();
}
System.out.println(filesrc.getName() + "文件夹复制成功");
}