文件流:
Io流:io包。
作用:读取数据和写入数据:
2.1按数据的流向来分。
都是以程序为参照物,如果是向程序里写入数据,则是读取数据或者输入数据,如果是从程序中向外界写数据,那么就是写入数据,或者输出数据
读数据的流:Input,Reander:从别的地方读数据到程序中
写数据的流:Output,Writer:从程序中写数据到别的地方
2.2:按数据的类型来分:
字节流: 一个字节一个字节(byte)的读或者写,字节流的类一般后缀为stream
字符流:一个字符一个字符(char)的读或者写,字符流是在字节流的基础上加上编码机制,字符流的类的后缀一般为Reader,Writer
文件操作方面的流:
3.1往文件里写入数据
FileOutputStream:文件写入字节流 可以操纵所有文件 字节流
FileInputSteam:文件输出字节流 可以操纵所有文件 字节流
FileReader:只能操纵文本文件,其他文件不行 字符流
FileWriter:只能操纵文本文件,其他文件不行 字符流
FileOutputStream
1.将流跟文件相关联,创建流对象
try {
//将流和文件关联,如果文件不存在,创建,如果文件存在则覆盖内容(FileOutputStream("E:\\aa.txt"))
//如果是(FileOutputStream("E:\\aa.txt"),true):这个是在原有的内容中添加
FileOutputStream fos=new FileOutputStream("E:\\aa.txt");
//准备数据
String string="我们很棒";
byte[] b=string.getBytes();
//将数据写入文件
fos.write(b);
//关闭流
fos.close();
} catch (Exceptione) {
e.printStackTrace();
}
1. 从键盘输入一行并写入文件:
Scanner iScanner=new Scanner(System.in);
byte[] b=iScanner.next().getBytes();
FileOutputStream fos = null;
for (int i = 0; i < b.length; i++) {
try {
fos=new FileOutputStream("E:\\aa.txt",true);
fos.write(b[i]);
} catch (Exception e) {
// TODO Auto-generatedcatch block
e.printStackTrace();
}
}
fos.close();
2. 从键盘输入多行数据:
Scanner iScanner=new Scanner(System.in);
String string="";
while (!iScanner.next().equals("886")) {
String a=iScanner.next();
string+=a;
}
FileOutputStream fos=new FileOutputStream("e:\\aaa.txt",true);
fos.write(string.getBytes());
3. 读取文件:
//文件读取流
//关联文件
try {
FileInputStream fis=new FileInputStream("e:\\aa.txt");
//读数据,读一个字节,文件读到末尾时返回-1
int num=-1;
while ((num=fis.read())!=-1) {
System.out.print((char)num);
}
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
4. 先将文件读到缓冲数组中:一般用于大文件的读写,效率高
FileInputStream fis=new FileInputStream("e:\\aa.txt");
//创建一个字节数组,一般定义为1024的倍数
//先将数据读入缓冲数组b中
int len=-1;//表示读到的数据,当读到文件的末尾时放回-1
byte[]b=new byte[1024];
while ((len=fis.read(b))!=-1) {
System.out.println(new String(b,0,len));
}
public static void copy(String path,String path1) throws Exception{
FileInputStream fis=new FileInputStream(path);
FileOutputStream fos=new FileOutputStream(path1);
//一边读,一边写
int b=-1;
while ((b=fis.read())!=-1) {
fos.write(b);
}
fos.close();
fis.close();
}
//读一堆,写一堆
public static void copy2(String path,String path1) throws Exception{
FileInputStream fis=new FileInputStream(path);
FileOutputStream fos=new FileOutputStream(path1);
byte[]b=new byte[1024];
int len=-1;
while ((len=fis.read(b))!=-1) {
fos.write(b, 0, len);
}
fos.close();
fis.close();
}
//一次性读写完,用于文件小的操作
public static void copy3(String path,String path1) throws Exception{
FileInputStream fis=new FileInputStream(path);
FileOutputStream fos=new FileOutputStream(path1);
//fis.available;返回文件的字节总数
byte[]b=new byte[fis.available()];
int len=-1;
while ((len=fis.read(b))!=-1) {
fos.write(b);
}
fos.close();
fis.close();
}
//读取图片
public static void copy4(String path,String path1) throws Exception{
FileInputStream fis=new FileInputStream(path);
FileOutputStream fos=new FileOutputStream(path1);
byte[]b=new byte[1024];
int len=-1;
while ((len=fis.read(b))!=-1) {
fos.write(b,0,len);
//记得如果使用缓冲区,用刷新,将内存的数据刷到流中
fos.flush();
}
fos.close();
fis.close();
}
//文件字符输出流字符流
FileWriter fw=new FileWriter("e:\\ee.txt");
//写数据
fw.write("呵呵呵呵");
//凡是字符流,必须刷新
fw.close();//先调用刷新的方法
//调用close方法的时候会先调用刷新的方法
//fileReader与filewriter的使用
public static void copy(String path,String path1) throws Exception{
FileReader reader=new FileReader(path);
FileWriter writer=new FileWriter(path1);
int len=-1;
char ch[]=new char[1024];
while ((len=reader.read(ch))!=-1) {
writer.write(ch, 0, len);
}
writer.close();
reader.close();
}
3.2流中的异常的处理:标准写法:
FileReader reader=null;
try {
reader=new FileReader("e:\\ee.txt");
char[]ch=new char[1024];
int len=-1;
while ((len=reader.read(ch))!=-1) {
System.out.println(new String(ch,0,len));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
1:io流:io包.
作用:读取数据和写入数据。
2;io流的分类:
2.1:按数据的流向来分。
都是以程序为参照物,如果是向程序里写入数据,则是读取数据。如果从程序中向外界写数据,那么就是写入数据。
读数据的流:Input,Reader:从别的地方读数据到程序中。
写数据的流:Output,Writer:从程序中写数据到别的地方。
2.2:按数据的类型来分
2.2.1:字节流:一个字节一个字节读或者写
字节流的类的后缀为Stream.
2.2.2;字符流:一个字符一个字符得读或者写
字符流是在字节流的基础上加了编码机制。
字符流的类的后缀为Reader,Writer.
3:文件操作方面的流.
3.1:往文件里写入数据。
FileOutputStream:文件写入字节流。
文件操作流:
FileInputStream:可以操作文本文件也可以操作图片或者音频等文件,
FileOutputStream:可以操作所有文件。
FileReader:只能操作文本文件,其他文件不行。
FileWriter:只能操作文件文本,必须要刷新。
3.2;流中的异常的处理。
复习:
FileInputStream;读取字节流
FileOutputStream:写入字节流
常用的方法:
Read():读取一个字节,返回改字节
Read(byte[]) 读取多个字节到数组中,返回读取的长度,如果读取长度为-1表示已经读到了结尾
Wirte():写一个字节
Write(byte[]):将数组中的多个字节读到流中。
FileReader:读取字符流
FileWriter:写入字符流
常用的方法:
Read;读取一个字符
Read(char[]):读取多个字符到ch数组中
Write():写一个字符
Write(char[]):将数组中的数据读到流中
Write(String str):将字符串中的字符写到流中
1.带缓冲区的流:Buffer
节点流:接的都是数据源或者(小管道)
处理流:在节点流的基础上才有处理流(在小管道基础上的大管道,大管道包小管道,不能直接连接数据源)
处理流的代表:BuffedInputStream,BufferedOutputStream,用法和FileOutputStream一样,只是接的是节点流
BufferedReader:带缓冲区的处理流
BufferedWrite:带缓冲区的处理流
转换流,InputStreamReader:将字节流转换为字符流
OutputStreamWriter 是字符流通向字节流的桥梁
//转换流:从字符转换为字节流
OutputStreamWriter osw = new OutputStreamWriter(os);
代码一:
FileInputStream fis=null;
BufferedInputStream bis=null;
try {
//定义一个节点流
fis=new FileInputStream("e:\\aa.txt");
//定义一个处理流
bis=new BufferedInputStream(fis);
//定义一个数组
byte[]b=new byte[1024];
int len=-1;
while ((len=bis.read(b))!=-1) {
System.out.println(new String(b,0,len));
}
} catch (FileNotFoundException e) {
// TODO Auto-generatedcatch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generatedcatch block
e.printStackTrace();
}finally{
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generatedcatch block
e.printStackTrace();
}
}
}
字符流:
public static void main(String[] args) {
FileReader fr=null;
BufferedReader br=null;
try {
fr=new FileReader("e:\\aaa.txt");
br=new BufferedReader(fr);
String string=null;
while ((string=br.readLine())!=null) {
System.out.println(string);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
br.close();
fr.close();
} catch (IOException e) {
// TODO Auto-generatedcatch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
FileReader fr=null;
FileWriter fw=null;
BufferedReader bReader=null;
BufferedWriter bw=null;
try {
fr=new FileReader("e:\\aaa.txt");
fw=new FileWriter("e:\\lfz.txt");
bReader=newBufferedReader(fr);
bw=newBufferedWriter(fw);
String string=null;
do {
string=bReader.readLine();
if (string==null) {
break;
}
bw.write(string);
bw.newLine();
} while (true);
} catch (FileNotFoundException e) {
// TODO Auto-generatedcatch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generatedcatch block
e.printStackTrace();
}finally{
try {
bw.close();
bReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
高效率用Buffered
装饰者模式:
package com.qianfeng.buffer;
public class Person {
publicvoid eat(){
System.out.println("吃树叶");
System.out.println("吃红薯");
}
}
//装饰模式。
class NewPerson{
privatePerson person;
publicNewPerson(Person person){
this.person= person;
}
//吃,增强的功能。
publicvoid eat_02(){
person.eat();
System.out.println("喝牛奶");
System.out.println("吃鲍鱼");
System.out.println("吃米饭");
}
}
自定义的BufferedRead
public class MyBufferedReader {
private Reader br;
public MyBufferedReader(Reader br){
this.br=br;
}
//方法读取一行数据
public String readLine() throws Exception{
StringBuilder sb=new StringBuilder();
int ch;
while (true) {
ch=br.read();
if (ch==-1) {
return null;
}
if (ch=='\r') {
continue;
}else if (ch=='\n') {
break;
}else {
sb.append((char)ch);
}
}
return sb.toString();
}
}
‘\r’:13
‘\n’:10
//获得键盘的录入 system.in;
//字节不好操作,需要将字节转换为字符
//转换流: 将字节流转换为字符流
例子:
public class test06 {
public static void main(String[] args) throws Exception {
InputStream is=System.in;
InputStreamReader isr=new InputStreamReader(is);
BufferedReader reader=new BufferedReader(isr);
FileWriter writer=new FileWriter("e:\\kk.txt");
String str=null;
while ((str=reader.readLine())!=null) {
if ("886".equals(str)) {
break;
}
writer.write(str);;
writer.write("\r\n");
writer.flush();//刷新的方法
}
writer.close();
}
}
//如果不刷新,只有在结束的时候才会将数据写入文件
//将文件中的数据,写到控制台上,字符流转换字节流
文件:
File:文件或者文件夹
判断一个文件是否存在:file.exists()
判断是否为文件: file.isFile();
创建文件: file.createNewFile();
创建当前目录:file.mkdir()
创建所有目录:file.mkdirs();
删除文件:file.delete();
删除文件:file.deleteOnExit();
获得最后更改时间:file.lastModified()
long time = file.lastModified();
//Date
Date date = new Date(time);
//格式化
SimpleDateFormat sdf = newSimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String dateString =sdf.format(date);
System.out.println("最后一次修改的时间:"+dateString);
文件的字节数量:file.length();
更改名字file.renameTo(new File("f:\\pp.txt"));
获得所有的盘符:file.listRoots()
数组是分配在内存中,所有ByteArrayInputStream ByteArrayOutputStream称为内存流
//从内存中读取数据,再将数据写到内存中。
ByteArrayInputStream bais =new ByteArrayInputStream("你们都很棒".getBytes());
//用这种流写入数据,其实是写到内存中。
ByteArrayOutputStream baos =new ByteArrayOutputStream();
//一边读,一边写
int i = -1;
while((i=bais.read())!=-1){//读一个字节
baos.write(i);//写一个字节
}
//如何获得写入到内存中的数据。
System.out.println(baos.toString());
//获得刚写进去的字节数组。
byte[] b =baos.toByteArray();
写入流:
打印流:PrintStream
public static void main(String[] args) throws Exception {
InputStream is=System.in;
PrintStreamps=new PrintStream("e:\\aaa.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String string=null;
while (true) {
string=br.readLine();
if("886".equals(string)){
break;
}
ps.print(string);
ps.print("\r\n");
}
ps.close();
is.close();
}
打印流:PrintWriter
InputStream is=System.in;
PrintWriter writer=new PrintWriter(System.out,true);
BufferedReaderreader=new BufferedReader(newInputStreamReader(is));
String string=null;
while (true) {
string=reader.readLine();
if ("886".equals(string)) {
break;
}
writer.print(string);
writer.print("\r\n");
writer.flush();
}
writer.close();
public static void main(String[] args) throws Exception {
InputStream is=System.in;
PrintWriter writer=new PrintWriter(System.out,true);
BufferedReader reader=new BufferedReader(new InputStreamReader(is));
String string=null;
while (true) {
string=reader.readLine();
if ("886".equals(string)) {
break;
}
writer.println(string);
}
writer.close();
reader.close();
}
public static void main(String[] args) throws Exception {
DataOutputStream dos=new DataOutputStream(new FileOutputStream("e:\\aaa.txt"));
byte b=12;
short s=456;
dos.write(b);
dos.writeShort(s);
//读数据
DataInputStream dis=new DataInputStream(new FileInputStream("e:\\aaa.txt"));
System.out.println(dis.readByte());
System.out.println(dis.readShort());
}
内存流:
//从内存中读取数据,再将数据写到内存中
ByteArrayInputStream bais=new ByteArrayInputStream("呵呵呵".getBytes());
//用这种流写入数据,其实是写到内存中
ByteArrayOutputStreambaos=new ByteArrayOutputStream();
//一边读一边写
int i=-1;
while ((i=bais.read())!=-1) {
baos.write(i);
}
//获取写入内存中的数据
System.out.println(baos.toString());
对象流:ObjectOutStream:对对象的持久保存,将对象写到文件中
如果一个对象需要持久保存,则这个对象必须可序列化,即实现Serializable。
不能持久保存的属性:静态的,transient关键字修饰的非静态的属性
publicclass ObjectOutputStreamDemo1 {
public static void main(String[] args)throws FileNotFoundException, IOException, ClassNotFoundException {
Student stu = newStudent("王兴红",22,"男");
ObjectOutputStream oos = newObjectOutputStream(new FileOutputStream("f:\\wang.txt"));
oos.writeObject(stu);//写入一个对象
// stu.sex= "女";
oos.close();
ObjectInputStream ois = newObjectInputStream(new FileInputStream("f:\\wang.txt"));
Object obj =ois.readObject();//根据class文件去读取一个对象
System.out.println(obj);
}
}