流的分类: 因为分类的方式不同,可以将流分为不同的类型:

(1)按照流向:分为 **输入流** 和 **输出流**。输入流:表示将数据读取到java程序(内存)中使用的流。 输出流:表示从java程序(内存)向外传输使用的流。
(2)按照读取的数据单元: 分为 **字节流** 和 **字符流**字节流 :一次性传输一个字节数据,将数据以字节的形式传输。字符流: 一次性传输一个字符(1、2或3个字节)数据,将数据以字符的形式传输。
(3)按照流的角色: 分为: **节点流** 和  **处理流**节点流:可以从或向一个特定的地方(节点)读写字节数据。处理流:是对一个已存在的流的连接和封装,通过所封装的流的功能调用实现数据读写。

结构图


输入输出流

1 字节输入流: InputStream类的常用方法

InputStream是一个抽象类,不能实例化对象。
方法名 描述
void close() 关闭此输入流并释放与该流关联的所有系统资源。
int read() 从输入流中读取数据的下一个字节。
int read(byte[] b) 从输入流中读取一定数量的字节,并将其存储在缓冲区数组b中。
int read(byte[] b,int off, int len) 将输入流中最多len个数据字节读入 byte 数组。

2 字节输出流:OutputStream类的常用方法

OutputStream是抽象类,不能实例化对象。
方法名 描述
void close() 关闭此输出流并释放与此流有关的所有系统资源。
void flush() 刷新此输出流并强制写出所有缓冲的输出字节。
void write(byte[] b) 将 b.length 个字节从指定的 byte 数组写入此输出流。
void write(byte[] b,int off, int len) 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流。
void write(int b) 将指定的字节写入此输出流

(1) 文件输入流FileInputStream

public class DemoFileInputStream { public static void main(String[] args) {
//创建被操作文件:此文件必须存在,否则读取时,抛出文件找不到异常 File file = new         File("test\\hello.txt");
//声明流,不初始化
FileInputStream fis = null;
try {//初始化流fis = new FileInputStream(file);//准备数组用来存储数据byte[] b = new byte[3]; //先定义一个变量,初始值是‐1int i = ‐1; //定义一个计数循环的变量int count = 0; //while循环读取while((i=fis.read(b))!=‐1) {count++; for(int j=0; j<i; j++) {System.out.print((char)b[j]);}}System.out.println(count);//计数:计算循环读取的次数} catch (FileNotFoundException e) { // TODO Auto‐generated catch block e.printStackTrace(); }catch (IOException e) {// TODO Auto‐generated catch block e.printStackTrace(); }finally {if(fis!=null) {try {fis.close();} catch (IOException e) {// TODO Auto‐generated catch block e.printStackTrace();}}}}}

(2)文件输出流FileOutputStream

public class TestFileOutputStream {public static void main(String[] args) {//向文件中写入数据 //在工程中创建一个test文件夹 //设计程序,向test\\hello.txt中写入hello world//第一步:创建被操作文件对象//当向一个文件中写入数据时,若文件不存在,程序会自动创建File file = new File("test\\hello.txt"); FileOutputStream fos = null; try {//第二步:创建流对象 fos = new FileOutputStream(file, true);//第三步:准备数据 String str = "hello world";byte[] b = str.getBytes();System.out.println(b.length); //第四步:使用流写入fos.write(b);}catch(IOException e) {e.printStackTrace();} finally { if(fos!=null) {try {//第五步:刷新流,关闭流fos.flush();fos.close();}  catch (IOException e) { // TODO Auto‐generated catch block e.printStackTrace();}} }} }

1 字符输入流
Reader类 Reader:是所有字符输入流的父类,为一个抽象类,不能实例化对象,使用它的子类FileReader类

public class FileReaderUsageDemo {
public static void main(String[] args) {//1.将文件的路径转换为File对象File file = new File("file/input1.txt");Reader reader = null;try {//2.实例化一个FileReader的对象reader = new FileReader(file);//3.定义一个数组char[] arr = new char[8];//4.定义一个int的变量int hasRead = 0;//5.循环读取while((hasRead = reader.read(arr)) != -1) {String result = new String(arr, 0, hasRead);System.out.println(result);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally {//避免出现空指针异常if(reader != null) {try {reader.close();} catch (IOException e) {e.printStackTrace();}}}
}
}

2 字符输出流
Writer类 Writer:是所有字符输出流的父类,为一个抽象类,不能实例化对象,使用它的子类FileWriter类

public class TestFileOutputStream {
public static void main(String[] args) {//向文件中写入数据//在工程中创建一个test文件夹//设计程序,向test\\hello.txt中写入hello world//第一步:创建被操作文件对象//当向一个文件中写入数据时,若文件不存在,程序会自动创建File file = new File("test\\hello.txt");FileOutputStream fos = null;try {//第二步:创建流对象fos = new FileOutputStream(file, true);//第三步:准备数据String str = "hello world";byte[] b = str.getBytes();System.out.println(b.length);//第四步:使用流写入fos.write(b);}catch(IOException e) {e.printStackTrace();} finally {if(fos!=null) {try {//第五步:刷新流,关闭流fos.flush();fos.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
}
}

转换流

作用:
a.实现字节流到字符流的转换
b.解决中文乱码的问题中文编码gb2312 (采用两个字节保存字符汉字,英文数字一个字节)GBK  (采用两个字节保存字符汉字,英文数字一个字节)GB18030 (英文数字都是一个字节,中文是两个或四个字节)Unicode字符集(包含每个国家的所有字符)国际通用unicode编码  使用两个字节---65536个字符,浪费空间为了节省空间使用转码形式utf-8       使用 1 、2、3个字节   (EF BB BF 记事本添加的BOM(Byte Order Mark)头,编码的标记)utf-16      使用两个字节---65536个字符   (FF FE 小端(尾) FE FF 大端(尾))utf-32      使用4个字节台湾  big5ANSI:在简体中文Windows操作系统中, ANSI 编码代表 GBK 编码只有转换流才能指定读取和写入的字符集

InputStreamReader:字节字符转换输入流,将字节输入流转换为字符输入流

public class InputStreamReaderDemo {
public static void main(String[] args) throws IOException {//1.实例化File的对象//File file = new File("file/input1.txt");//2.实例化转换输入流的对象//注意:当一个流的存在的意义是为了实例化另外一个流,则这个流不需要手动进行关闭//InputStream input = new FileInputStream(file);//InputStreamReader reader = new InputStreamReader(input);//使用默认的字符集【GBK】进行实例化转换流//InputStreamReader reader = new InputStreamReader(new FileInputStream(new File("file/input1.txt")));//使用指定字符集进行实例化转换流//字符集一般使用字符串直接传参,不区分大小写,但是,如果字符集书写有误的话,则会跑出java.io.UnsupportedEncodingExceptionInputStreamReader reader = new InputStreamReader(new FileInputStream(new File("file/input1.txt")),"UTF-8");//3.读取char[] arr = new char[16];int len = 0;while((len = reader.read(arr)) != -1) {String string = new String(arr, 0, len);System.out.println(string);}reader.close();
}
}

OutputStreamWriter:字符转换输出流,将内存中的字符转成字节保存到硬盘中。

public class OutputStreamWriterDemo {
public static void main(String[] args) throws IOException {//需求:将一段文本以utf-8的格式写入到文件中【注,文件格式为默认格式】//1.实例化FIle对象//注意:对于所有的输出流而言,文件可以不存在,在进行写入的过程中可以自动进行创建//但是,对于所有的输入流而言,文件必须先存在,然后才能操作,否则,会抛出FileNotFounedExceptionFile file = new File("file/output1.txt");//2.实例化转换输出流//如果不想覆盖源文件中的内容时,则在传参的时候,设置一个参数为trueOutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file,true), "utf-8");//3.写入writer.write("家客户放假啊刚回家");//4.刷新writer.flush();//5.关闭writer.close();
}
}

缓冲流

作用:主要是为了增强基础流的功能而存在的,提高了流的工作效率【读写效率】
注意:如果使用记事本创建的文件,文件是utf-8或者unicode编码,文件的前面
有一个BOM(ByteOrder Mark)头,BOM作用指定文件使用的编码类型
GBK编码没有添加bom头。
utf-8:EF BB BF
unicode 小端: FF FE     66 00
unicode 大端 :FE FF    00 66

1 BufferedInputStream类

public class BufferedInputStreamDemo {
public static void main(String[] args) throws IOException {//实例化一个File对象File file = new File("file/test22.txt");//实例化一个缓冲字节输入流的对象BufferedInputStream input = new BufferedInputStream(new FileInputStream(file));/*//读取byte[] arr = new byte[1024];int len = 0;while((len = input.read(arr)) != -1) {String string = new String(arr, 0, len);}*/byte[] arr = new byte[4];int len = input.read(arr);String string = new String(arr, 0, len);System.out.println(string);input.mark(66);len = input.read(arr);string = new String(arr, 0, len);System.out.println(string);// 实现了效果:覆水可收input.reset();len = input.read(arr);string = new String(arr, 0, len);System.out.println(string);input.close();
}
}

2 BufferedOutputStream类

public class BufferedOutputStreamDemo {
public static void main(String[] args) throws IOException {//实例化FIle对象File file = new File("test33.txt");//实例化换种字节输出流 BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(file));//写output.write("你好的halle".getBytes());//刷新output.flush();//关闭output.close();
}
}

3 BufferedReader类

public class BufferedReaderDemo {
public static void main(String[] args) throws IOException {//实例化FIle对象File file = new File("test33.txt");//实例化缓冲字符流的对象BufferedReader reader = new BufferedReader(new FileReader(file));//方式一:read循环读取/*//读取char[] arr = new char[8];int len = 0;while((len = reader.read(arr)) != -1) {String string = new String(arr, 0, len);}*///方式二:readLine循环读取/*String result1 = reader.readLine();System.out.println(result1);String result2 = reader.readLine();System.out.println(result2);*/String result = "";while((result = reader.readLine()) != null) {System.out.println("第一行:" + result);}reader.close();
}
}

4 BufferedWriter类

public class BufferedWriterDemo {
public static void main(String[] args) throws IOException {
// 实例化FIle对象
File file = new File(“test33.txt”);

 //实例化缓冲字符输出流BufferedWriter writer = new BufferedWriter(new FileWriter(file,true));// 写writer.write("今天天气还可以");// 作用:主要就是为了换行writer.newLine();// 刷新writer.flush();//关闭writer.close();}

内存流

输入和输出都是从文件中来的,当然,也可将输出输入的位置设置在内存上,这就需要ByteArrayInputStream和 ByteArrayOutputStream

ByteArrayInputStream:将内容写入到内存中,是Inputstream的子类
ByteArrayOutputStream:将内存中数据输出,是OutputStream的子类此时的操作应该以内存为操作点

构造方法及常用方法
ByteArrayInputStream

ByteArrayInputStream(byte[] buf)
创建一个 ByteArrayInputStream ,使其使用 buf作为其缓冲区数组。
ByteArrayInputStream(byte[] buf, int offset, int length)
创建 ByteArrayInputStream使用 buf作为其缓冲器阵列。  int available() ;  返回可从此输入流读取(或跳过)的剩余字节数。
void close()  ;关闭 ByteArrayInputStream没有任何效果。
void mark(int readAheadLimit)  设置流中当前标记的位置。
boolean markSupported() ;测试 InputStream是否支持标记/复位。
int read() ;从该输入流读取下一个数据字节。
int read(byte[] b, int off, int len)   ;  将 len字节的数据读入此输入流中的字节数组。
void reset() ; 将缓冲区重置为标记位置。
long skip(long n) 从此输入流跳过 n个字节的输入。

ByteArrayOutputStream

构造方法及常用方法

ByteArrayOutputStream()
创建一个新的字节数组输出流。
ByteArrayOutputStream(int size)
创建一个新的字节数组输出流,具有指定大小的缓冲区容量(以字节为单位)。  void close() ;          关闭 ByteArrayOutputStream没有任何效果。
void reset() ;         将此字节数组输出流的 count字段重置为零,以便丢弃输出流中当前累积的所有输出。
int size() ;               返回缓冲区的当前大小。
byte[] toByteArray() ;   创建一个新分配的字节数组。
String toString(); 使用平台的默认字符集将缓冲区内容转换为字符串解码字节。
(将内容从内存输出到控制台常用的两个)void write(byte[] b, int off, int len); 从指定的字节数组写入 len字节,从偏移量为 off开始,输出到这个字节数组输出流。
void write(int b) ;将指定的字节写入此字节数组输出流。
void writeTo(OutputStream out)  ;将此字节数组输出流的完整内容写入指定的输出流参数,就像使用        out.write(buf, 0, count); 调用输出流的写入方法 out.write(buf, 0, count) 。

使用内存流读写数据和完成大小写转换

ackage com.qf.day18;import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;/*** 使用内存流读写数据* * @author wgy**/
public class Demo6 {public static void main(String[] args) throws Exception{//read();//write();String s=toUpperCase("hello");System.out.println(s);}public static void read() throws Exception{String s="helloworld";//数据源byte[] data=s.getBytes();//1创建流ByteArrayInputStream bais=new ByteArrayInputStream(data);//2读取int d=-1;while((d=bais.read())!=-1) {System.out.print((char)d);}//3关闭bais.close();}public static void write() throws Exception{//1创建内存流ByteArrayOutputStream baos=new ByteArrayOutputStream();//内部维护一个保存数据的数组//2写入baos.write(97);baos.write(98);baos.write(99);//3关闭baos.close();String data=baos.toString();  //获取写到内存中的数据
//      或 byte [] a =baos.toByteArray();System.out.println(data);}//使用内存流实现小写转成大写字母public static String toUpperCase(String str) throws Exception{byte[] bs=str.getBytes();//1创建内存流ByteArrayInputStream bais=new ByteArrayInputStream(bs);ByteArrayOutputStream baos=new ByteArrayOutputStream();int d=-1;//2读写while((d=bais.read())!=-1) {char c=(char)d;char c2=Character.toUpperCase(c);baos.write(c2);}//3关闭bais.close();baos.close();return baos.toString();
}}

注意:内存操作流的操作对象,一定是以内存为主准,不要以硬盘为准 。

标准输入输出流
Java的标准输入/输出分别通过System.in和System.out实现,默认情况下分别代表是键盘和显示器

PrintStream(File file)
使用指定的文件创建一个新的打印流,而不需要自动换行。
PrintStream(File file, String csn)
使用指定的文件和字符集创建新的打印流,而不需要自动换行。
PrintStream(OutputStream out)
创建一个新的打印流。
PrintStream(OutputStream out, boolean autoFlush)
创建一个新的打印流。
PrintStream(OutputStream out, boolean autoFlush, String encoding)
创建一个新的打印流。
PrintStream(String fileName)
使用指定的文件名创建新的打印流,无需自动换行。
PrintStream(String fileName, String csn)
创建一个新的打印流,不需要自动换行,具有指定的文件名和字符集。

PrintStream类:PrintStream为其他输出流添加了功能,使它们能够方便地打印各种数据值表示形式。

一些常用方法:

PrintStream append(char c)
将指定的字符附加到此输出流。
PrintStream append(CharSequence csq)
将指定的字符序列附加到此输出流。
PrintStream append(CharSequence csq, int start, int end)
将指定字符序列的子序列附加到此输出流。  void print(boolean b)      打印布尔值。
void print(char c)      打印一个字符
void print(char[] s)      打印字符数组。
void print(double d)      打印双精度浮点数。
void print(float f)        打印浮点数。
void print(int i)       打印一个整数。
void print(long l)          打印一个长整数。
void print(Object obj)      打印一个对象。
void print(String s)        打印字符串。
PrintStream printf(Locale l, String format, Object... args)
使用指定的格式字符串和参数将格式化的字符串写入此输出流的便利方法。
PrintStream printf(String format, Object... args)
使用指定的格式字符串和参数将格式化的字符串写入此输出流的便利方法。
void println()    通过写入行分隔符字符串来终止当前行。
void println(boolean x)    打印一个布尔值,然后终止该行。
void println(char x)     打印一个字符,然后终止该行。
void println(char[] x)    打印一个字符数组,然后终止该行。
void println(double x)      打印一次,然后终止行。
void println(float x)        打印一个浮点数,然后终止该行。
void println(int x)          打印一个整数,然后终止行。
void println(long x)        打印很长时间,然后终止行。
void println(Object x)          打印一个对象,然后终止该行。
void println(String x)          打印一个字符串,然后终止行。
void write(byte[] buf, int off, int len)
从指定的字节数组写入 len个字节,从偏移 off开始到此流。
void write(int b)    将指定的字节写入此流。

重定向:

System类里的方法:

static void setErr(PrintStream err);    重定向“标准” 错误输出流。
static void setIn(InputStream in);      重定向“标准” 输入流。
static void setOut():                   重定向“标准” 输出流;

重定向到文件输出:

 public class ReadirectOut{public static void main(String [] args){try{PrintStream psi = new PrintStream(new FileOutputStream("out.txt"));System.out.setOut(psi);System.out.println("本应输出到控制台的字符串和整型3:"+3);System.out.println("输出对象:"+new ReadirectOut);}catch(IOException ex){ex.printStackTrce();}
}

重定向到标准输入:

public class ReadirectIn{public static void main(String [] args){try{FileInputStream sis = new FIleInputStream("ReadirectIn.java");System.setIn(fis);//使用System.in 创建Scanner对象,用于获取标准输入Scanner  sc = new Scanner(System.in);//增加下面一行 只把回车作为换行符sc.useDelimiter("\n");while(sc.hasNext){System.out.println("键盘输入的内容是:"+sc.next);}}catch(IOexception s){s.printStackTrace();}}
}

从控制台读取数据

public class Demo8 {public static void main(String[] args)throws  Exception {InputStream is = System.in;//2读取数据int d1 = is.read();System.out.println((char)d1); // 不可输入汉字int d =-1;StringBuilder sb = new StringBuilder();while ((d=is.read())!=0){if(d==13){continue;}if(d==10){System.out.println(sb.toString());if(sb.toString().equals("over")){break;}sb.delete(0,sb.length() );}else {sb.append((char)d);}}is.close();}}public class Demo9 {public static void main(String[] args) throws Exception{//InputStream is =System.in;InputStreamReader isr  = new InputStreamReader(System.in) ;BufferedReader br = new BufferedReader(isr);String line = null;while (true){line = br.readLine();System.out.println(line);if(line.equals("over")){break;}}}
}

对象流(序列化)

流中流动的数据是对象将一个对象写入到本地文件中,被称为对象的序列化将一个本地文件中的对象读取出来,被称为对象的反序列化
使用对象流ObjectInputStream: 对象输出流ObjectOutputStream:对象输入流注意:序列化对象的类型必须实现Serializable接口。否则不能序列化。如果向将多个对象序列化到本地,可以借助于集合,【思路:将多个对象添加到集合中,将集合的对象写入到本地文件中,再次读出来,获取到的仍然是集合对象,遍历集合】。
对象中那些字段可以不序列化:1 transient 修饰的字段2 静态的字段
在要序列化类中添加字段,保证序列化和反序列化是同一个类
private static final long serialVersionUID = 100L;

序列化对象类Student 需要实现Serializable 接口

public class Student implements Serializable {private String  name;private int age;private  String address;public Student(){}public Student(String name,int age,String address){this.name = name;this.age = age;this.address = address;}public  String  getName(){return  name;}public void setName(String name){this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}public String toString (){return "Student{"+"name,"+name+",age:"+age+",address:"+address+"}";}
}//   注释部分为 单个添加
public class Demo12 {public static void main(String[] args) throws Exception{//序列化ObjectOutputStream sb = new ObjectOutputStream(new FileOutputStream("stu.txt"));Student s1 = new Student("bb",23,"北京");Student s2 = new Student("cc",22,"太原");Student s3 = new Student("dd",18,"北京");ArrayList<Student> sd = new ArrayList<>();sd.add(s1);sd.add(s2);sd.add(s3);sb.writeObject(sd);//  sb.writeObject(s1);// sb.writeObject(s2);ObjectInputStream sc = new ObjectInputStream(new FileInputStream("stu.txt"));//Student s11 =(Student) sc.readObject();// Student s22 =(Student) sc.readObject();ArrayList<Student> df =(ArrayList<Student>) sc.readObject();System.out.println(df.toString());// System.out.println(s11.toString());// System.out.println(s22.toString());}
}

随机读取流 RandomAccessFile类

该类的实例支持读取和写入随机访问文件。

RandomAccessFile是用来访问那些保存数据记录的文件的,你就可以用seek( )方法来
访问记录,    并进行读写了。这些记录的大小不必相同;但是其大小和位置必须是可知的。
但是该类仅限于操作文件。

构造方法

(File file, String mode)
创建一个随机访问文件流从File参数指定的文件中读取,并可选地写入文件。
RandomAccessFile(String name, String mode)
创建随机访问文件流,以从中指定名称的文件读取,并可选择写入文件。

常用方法

void close()       关闭此随机访问文件流并释放与流相关联的任何系统资源。
long length()      返回此文件的长度。
int read()
从该文件读取一个字节的数据。
int read(byte[] b)
从该文件读取最多 b.length字节的数据到字节数组。
int read(byte[] b, int off, int len)
从该文件读取最多 len个字节的数据到字节数组。
boolean readBoolean()
从此文件读取一个 boolean 。
byte readByte()
从此文件中读取一个带符号的八位值。
char readChar()
从此文件中读取一个字符。
double readDouble()
从此文件读取 double 。
float readFloat()
从此文件读取一个 float 。
int readInt()
从该文件读取一个带符号的32位整数。
String readLine()
从此文件中读取下一行文本。
long readLong()
从该文件中读取一个带符号的64位整数。
short readShort()
从此文件中读取一个已签名的16位数字。
void seek(long pos)
设置文件指针偏移,从该文件的开头测量,发生下一次读取或写入。  void write(byte[] b)
从指定的字节数组写入 b.length个字节到该文件,从当前文件指针开始。
void write(byte[] b, int off, int len)
从指定的字节数组写入 len个字节,从偏移量 off开始写入此文件。
void write(int b)
将指定的字节写入此文件。
void writeBoolean(boolean v)
将 boolean写入文件作为一个字节值。
void writeByte(int v)
将 byte写入文件作为单字节值。
void writeBytes(String s)
将字符串作为字节序列写入文件。
void writeChar(int v)
将 char写入文件作为两字节值,高字节为先。
void writeChars(String s)
将一个字符串作为字符序列写入文件。
void writeDouble(double v)
双参数传递给转换 long使用 doubleToLongBits方法在类 Double ,然后写入该 long值到该文件作为一个八字节的数量,高字节。
void writeFloat(float v)
浮子参数的转换 int使用 floatToIntBits方法在类 Float ,然后写入该 int值到该文件作为一个四字节数量,高字节。
void writeInt(int v)
将 int写入文件为四个字节,高字节 int 。
void writeLong(long v)
将 long写入文件为八个字节,高字节为先。
void writeShort(int v)
将 short写入文件作为两个字节,高字节优先。

案例一:RandomAccessFile类的应用

public class TextDemo01 {public static void main(String[] args) throws Exception {RandomAccessFile file = new RandomAccessFile("file.txt", "rw");// 以下向file文件中写数据file.writeInt(20);// 占4个字节file.writeDouble(8.236598);// 占8个字节//这个长度写在当前文件指针的前两个字节处,可用readShort()读取file.writeUTF("这是一个UTF字符串");file.writeBoolean(true);// 占1个字节file.writeShort(395);// 占2个字节file.writeLong(2325451l);// 占8个字节file.writeUTF("又是一个UTF字符串");file.writeFloat(35.5f);// 占4个字节file.writeChar('a');// 占2个字节//把文件指针位置设置到文件起始处file.seek(0);// 以下从file文件中读数据,要注意文件指针的位置System.out.println("——————从file文件指定位置读数据——————");System.out.println(file.readInt());System.out.println(file.readDouble());System.out.println(file.readUTF());//将文件指针跳过3个字节,本例中即跳过了一个boolean值和short值。file.skipBytes(3);System.out.println(file.readLong());//跳过文件中“又是一个UTF字符串”所占字节//注意readShort()方法会移动文件指针,所以不用写2。file.skipBytes(file.readShort()); System.out.println(file.readFloat());// 以下演示文件复制操作System.out.println("——————文件复制(从file到fileCopy)——————");file.seek(0);RandomAccessFile fileCopy = new RandomAccessFile("fileCopy.txt", "rw");int len = (int) file.length();// 取得文件长度(字节数)byte[] b = new byte[len];//全部读取file.readFully(b);fileCopy.write(b);System.out.println("复制完成!");}}

Properties类

是Map接口的一个实现类,并且是Hashtable的子类

Properties集合中元素也是以键值对的形式存在的

Properties特点:
1 存储属性名和属性值
2 属性名和属性值都是字符串
3 和流有关系
4 没有泛型

构造方法

Properties()
创建一个没有默认值的空属性列表。
Properties(Properties defaults)
创建具有指定默认值的空属性列表。

普通方法

String getProperty(String key)
使用此属性列表中指定的键搜索属性。
String getProperty(String key, String defaultValue)
使用此属性列表中指定的键搜索属性。
void list(PrintStream out)
将此属性列表打印到指定的输出流。
void list(PrintWriter out)
将此属性列表打印到指定的输出流。
void load(InputStream inStream)
从输入字节流读取属性列表(键和元素对)。
**void load(Reader reader)
以简单的线性格式从输入字符流读取属性列表(关键字和元素对)。
void loadFromXML(InputStream in)
将指定输入流中的XML文档表示的所有属性加载到此属性表中。
Enumeration<?> propertyNames()
返回此属性列表中所有键的枚举,包括默认属性列表中的不同键,如果尚未从主属性列表中找到相同名称的键。
void save(OutputStream out, String comments)
已弃用
如果在保存属性列表时发生I / O错误,此方法不会抛出IOException。 保存属性列表的store(OutputStream out, String comments)方法是通过store(OutputStream out, String comments)方法或storeToXML(OutputStream os, String comment)方法。
Object setProperty(String key, String value)
致电 Hashtable方法 put 。
**void store(OutputStream out, String comments)
将此属性列表(键和元素对)写入此 Properties表中,以适合于使用 load(InputStream)方法加载到 Properties表中的格式输出流。
void store(Writer writer, String comments)
将此属性列表(键和元素对)写入此 Properties表中,以适合使用 load(Reader)方法的格式输出到输出字符流。
void storeToXML(OutputStream os, String comment)
发出表示此表中包含的所有属性的XML文档。
void storeToXML(OutputStream os, String comment, String encoding)
使用指定的编码发出表示此表中包含的所有属性的XML文档。
Set<String> stringPropertyNames()
返回此属性列表中的一组键,其中键及其对应的值为字符串,包括默认属性列表中的不同键,如果尚未从主属性列表中找到相同名称的键。

列子1

public  class PropertiesTest{public static void main() throws Exception{Properties  prop = new Properties();//System.out.println(prop);prop.setProperty("aa", "21");prop.setProperty("bb", "23");prop.setProperty("cc", "23");//System.out.println(prop);System.out.println(prop.get("aa"));//将properties 中的key-value 保存到a.txt中。prop.store(new FileWriter("a.txt"), "comment line");Properties prop2 = new Properties(); prop2.setProperty("key2","value2" );//把a.txt 文件读取出来加到prop2中prop2.load(new FileInputStream("a.txt"));System.out.println(prop2);}
}
输出结果为:
21
{key2=value2, aa=21, bb=23, cc=23}

列子2

public class PropertiesDemo {public static void main(String[] args) {//1.实例化一个Properties的对象Properties pro = new Properties();System.out.println(pro);//2.把文件userlist.properties中的键值对同步到集合中//实质:读取/***  void load(InputStream inStream) 从输入流中读取属性列表(键和元素对)。 */try {pro.load(new BufferedInputStream(new FileInputStream(new File("file/userlist.properties"))));} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println(pro);//3.向集合中添加一对键值对/**  Object setProperty(String key, String value) 调用 Hashtable 的方法 put。 * */pro.setProperty("address", "china");System.out.println(pro);try {//4.store//实质:写入//comments:工作日志pro.store(new BufferedOutputStream(new FileOutputStream(new File("file/userlist.properties"))), "add a pair of key and value");} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}
}

装饰者设计模式

装饰模式指的是在不必改变原类文件和继承的情况下,动态地扩展一个对象的功能。         它是通过创建一个包装对象,也就是装饰来包裹真实的对象。
应用场景:需要扩展一个类的功能,或给一个类添加附加职责。

案例:

1 抽象类 ReadFile -->read抽象方法
2 定义一些子类ReadTextFile 读取文本文件ReadMusicFile 读取音乐文件ReadVideoFile 读取视频文件
3 要求:提高三个类的功能:带缓冲    3.1继承BufferedReadTextFile继承ReadTextFile 重写 read方法BufferedReadMusicFile继承ReadMusicFile 重写 readBufferedReadVideoFile继承ReadVideoFile 重写 read缺点:1 类体系太庞大 2 耦合性太高3.2装饰者设计模式 :采用组合的关系BufferedReadFile{private ReadFile readFile;public BufferedReadFile(ReadFile readFile){this.readFile=readFile;}public void read(){///}}优点:耦合性低,提高重用性

代码实现

/*** 抽象人类* @author wgy**/
public abstract class AbstractPerson {public abstract void eat();
}/**
*子类1
*/
public class Person extends AbstractPerson {String name;public void eat() {System.out.println(name+"正在吃东西.........");}}package com.qf.day18_6;
/*** 子类2* @author wgy**/
public class Person2 extends AbstractPerson{String name;@Overridepublic void eat() {System.out.println(name+"吃......");}}
public class StrongPerson extends AbstractPerson {//使用person创建一个变量AbstractPerson p;public StrongPerson(AbstractPerson p) {this.p = p;}public void eat() {p.eat();System.out.println("抽一口");System.out.println("眯一会");System.out.println("写会java代码");}}//测试类
package com.qf.day18_6;public class Test {public static void main(String[] args) {Person benwei=new Person();benwei.name="本伟";Person2 zhengshuai=new Person2();zhengshuai.name="郑帅";StrongPerson strongPerson=new StrongPerson(benwei);StrongPerson strongPerson2=new StrongPerson(zhengshuai);strongPerson.eat();strongPerson2.eat();}
}

Java-----关于IO流的总结相关推荐

  1. Java基础—IO流

    第一讲   IO概述 1. 流的概念 IO流即InputOutput的缩写,在Java中IO流用来处理设备之间的数据传输,Java对数据的操作是通过IO流的方式, 我们可以把IO流抽象的当作一根管道, ...

  2. java数据通道抽象为流_【java】IO流

    对于java的IO流的理解很长时间来都是很乱,包括学习其他的语言对这一块知识也都算是一个盲点.更多的时候一提到读取保存数据就是使用数据库.这一次学习了IO流,自己又解决了一个很大的盲点. IO流为我们 ...

  3. 第15章-输入/输出 --- 理解Java的IO流

    (一)理解Java的IO流 JAVA的IO流是实现输入/输出的基础,它可以方便地实现数据的输入/输出操作,在Java中把不同的输入/输出(键盘.文件.网络连接等)抽象表述为"流"( ...

  4. Java基础-IO流对象之数据流(DataOutputStream与DataInputStream)

    Java基础-IO流对象之数据流(DataOutputStream与DataInputStream) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.数据流特点 操作基本数据类型 ...

  5. Java中IO流的总结

    有关Java中IO流总结图 流分类 按方向分 输入流 输出流 按单位分 字节流 字符流 按功能分 节点流 处理流(过滤流) 其他 所有的流继承与这四类流:InputSteam.OutputStream ...

  6. Java 的 IO 流

    接着上一篇的 "Java 的 File 类" 的随笔,在File类的基础上,我们就走进Java的IO流吧. 流的概念和作用 流是一组有顺序的,有起点和终点的字节集合,是对数据传输的 ...

  7. java中io流是类吗_Java中的IO流

    今天刚刚看完java的io流操作,把主要的脉络看了一遍,不能保证以后使用时都能得心应手,但是最起码用到时知道有这么一个功能可以实现,下面对学习进行一下简单的总结: IO流主要用于硬板.内存.键盘等处理 ...

  8. Java - 文件(IO流)

    Java - 文件 (IO) 流的分类:     > 文件流:FileInputStream | FileOutputStream | FileReader | FileWriter     & ...

  9. java 的io流需要学吗_Java的IO流之字节流,必须要学得内容,你会嘛?

    原标题:Java的IO流之字节流,必须要学得内容,你会嘛? 伙伴们~ 端午节过的如何呀~ 有没有很开心呀~ 假期已过咱们继续开动了 IO流 先来认识一下IO流: IO流用来处理设备之间的数据传输,Ja ...

  10. 总是记不住java的IO流用法?用N个问题教你掌握java IO流

    本文分享自华为云社区<总是记不住java的IO流用法?用N个问题教你掌握java IO流>,原文作者:breakDraw . Java IO 体系看起来类很多,感觉很复杂,但其实是 IO ...

最新文章

  1. 泡沫破裂之后,强化学习路在何方?
  2. 使用asm工具让移动设备投影到pc上
  3. MFC显示位图 from http://blog.csdn.net/liuzhuomju/article/details/7299458
  4. bat里如何用相对路径
  5. 大学期间承接软件项目的一些个人观点
  6. .bat脚本自动yes_第四章: Python脚本获取聚宽(JQData)免费行情数据
  7. SpringBoot中使用类型安全的配置来注入大量自定义属性
  8. CSS3之border
  9. 软件测试行业有哪些细分方向,软件测试人员有哪些职业发展方向?
  10. SpringCloud Gateway的组成结构
  11. linux 常用命令03--修改文件的权限与归属
  12. 面试刷题29:mysql事务隔离实现原理?
  13. 2021福州地区高考成绩排名查询,2021年福州各高中高考成绩排名及放榜最新消息...
  14. LeetCode热题100使用摩尔投票法的题目整理(待更)
  15. 【测试】使用selenium实现QQ邮箱登录
  16. 连续英文字符串分词工具wordninja添加自定义名词
  17. IMSI前5位对应移动运营商名称的列表
  18. 低延迟平价游戏蓝牙耳机推荐,2021值得入手的五款品牌蓝牙耳机
  19. 天津市雏鹰企业认定奖励及申报标准介绍,补贴5万
  20. Android Spans介绍(转)

热门文章

  1. 荣耀magicbook15C语言,荣耀MagicBook 15 2021版评测:轻薄机身+强悍性能 专为高效率办公而生...
  2. 关于三栏式布局的几种方式
  3. node.js中express框架的使用
  4. 科目二 后视镜 调节
  5. GoLang之defer、panic、recover
  6. c语言cm 英尺换算
  7. 谷歌关闭中国地区音乐搜索服务与产品设计
  8. 阿里云服务器迁移内容
  9. wex5 php开发,WeX5开发移动APP(SQLite本地数据优化)
  10. JNCIS-FWV Study Guide v1.3