字节流
FileOutputStream
FileOutputStream fos = new FileOutputStream("mydir\\a.txt");//写入文件路径
String str = "fdsfs";
fos.write(str.getBytes());
//如果要换行写
String warp = "\r\n";
fos.write(warp.getBytes());
//续写
fos = new FileOutputStream("mydir\\a.txt",true);//接着写不清空 默认false
FileInputStream
try (FileInputStream fis = new FileInputStream("mydir:\\movie.mp4");//读流
FileOutputStream fos = new FileOutputStream("mydir\\copy.mp4")//写流){
//拷贝核心思想:边读边写
int len;
byte[] bytes = new byte[1024*1024];//一次拷贝1MB
while((len = fis.read(bytes)) != -1){
fos.write(bytes,0,1024);
}
}catch(IOException e){
e.printStackTrace();
}
字符集
windows常用ANSI 就是GBK字符集 ,一个字符两字节 中文以1开头 英文以0开头,方便区别。
乱码
- 不要用字节流读取文本文件
- 编码解码时使用同一个码表,同一个编码方式
字符流
字符流输入流的无参read方法:默认一个字节一个字节读取,遇到中文读多个字节,遇到英文读取一个字节,读取之后按照编码方式转换为十进制,要显示数值可以强转为char
字符流的带参read(char[] buffer)方法:字节流的read方式传递bytes数组,这里是字符数组,把读取字节解码和强转三部合并,强转之后的字符放到数组中了
字符输出流
FileReader fr = new FileReader("mydir\\a.txt");
fr.read();//读到缓冲区 fr 在内存有一个8000字节的缓冲区
FileWriter fw = new FileWriter("mydir\\a.txt");//这是清空写
int ch;
while((ch = fr.read())!=-1){
System.out.println((char)ch);
}
字符输出流原理:与字节流输出没有缓存区,字符流有一个内存缓冲区,fr.read会首先写到缓冲区,当刷新或缓冲区装满了或调用flush方法会更新文件。
拷贝文件夹
private static void copydir(File src,File dest) throws IOException {
dest.mkdirs();
//递归
File[] files = src.listFiles();
for(File file:files){
if(file.isFile()){
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(new File(dest,file.getName()));//
int len;
byte[] bytes = new byte[1024];
while((len = fis.read(bytes))!=-1){
fos.write(bytes);
}
}else{
//判断为文件夹
copydir(file,new File(dest,file.getName()));
}
}
}
缓冲流
利用缓存流拷贝
//创建缓冲流的对象
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(""));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(""));
byte[] bytes = new byte[1024];
int len;
while((len = bis.read(bytes))!=-1){
bos.write(bytes);
}
//释放资源
bos.close();
bis.close();//不需要关闭基本流
字符缓存流
由于字符流本身自带缓冲区,所以对IO的提升不算太大。但是有两个特有方法值得考虑
字符缓存输入流的特有方法:
public String readLine();//读取一行数据 读完返回null
字符缓存输出流的特有方法:
public String newLine();//针对不同的平台换行