黑马程序员——Java基础---IO(输入输出)(下)
来源:互联网 发布:印度经济 知乎 编辑:程序博客网 时间:2024/05/29 02:54
------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------
IO(流)目录:
一、IO流_字节流
1、IO流_字节流_输出流_FileOutputStream
2、IO流_字节流_输出流_输出换行和追加写入
3、IO流_字节流_输出流_加入异常处理
4、IO流_字节流_输入流_FileInputStream
5、IO流_字节流_练习_复制一个文本文件
6、IO流_字节流_练习_复制一个图片文件
7、IO流_字节流_带缓冲的字节流
8、IO流_练习_四种方式复制视频文件
二、String类编码_解码的方式
三、转换流
1、转换流_OutputStreamWriter
2、转换流_InputStreamReader
3、字符流_FileWriter_FileReader
4、字符流_缓冲流_BufferedWriter_BufferedReader
5、练习_字符流_读写文件的五种方式
四、其他流
1、数据操作流_DataInputStream_DataOutputStream
2、字节缓冲流_ByteArrayOutputStream_ByteArrayInputStream
3、打印流_PrintStream_PrintWriter
4、练习_打印流复制文本文件
5、打印流_PrintStream_输出语句的本质
6、标准输入流_三种方式实现键盘录入
7、随机访问流_RandomAccessFile类
8、序列化流_ObjectOutputStream_ObjectInputStream
9、Properties类_作为Map的基本功能
10、Properties类_操作配置文件
11、Properties类_判断文件中是否有指定的键如果有就修改值的案
12、NIO的介绍和JDK7下NIO的一个案例
五、练习
1、练习_把集合中的数据存储到文本文件案例
2、练习_把文本文件中的数据存储到集合中案例
3、练习_随机获取文本文件中的姓名案例
4、练习_复制单级文件夹案例
5、练习_复制指定目录下指定后缀名的文件并修改名称案例
IO(流)知识详解:
一、IO流_字节流
1、IO流_字节流_输出流_FileOutputStream
* IO流:
* 按读、写方式分:
* 1.字节流:
* 1).输出流:OutputStream(抽象类)
* |--FileOutputStream(类):
* 2).输入流:InputStream(抽象类)
* 2.字符流:
* 1).输出流:Writer(抽象类)
* 2).输入流:Reader(抽象类)
* 练习:
* 1.向文件中写入一句话:HelloWorld;
* 分析:
* 1.输出流:FileOutputStream:
* 构造方法:文件可以不存在,会自动创建一个新的;
* FileOutputStream(String name) :创建一个向具有指定名称的文件中写入数据的输出文件流。
* FileOutputStream(String name, boolean append) 创建一个向具有指定 name 的文件中写入数据的输出文件流。
* FileOutputStream(File file)创建一个向指定 File 对象表示的文件中写入数据的文件输出流。
* FileOutputStream(File file, boolean append)创建一个向指定 File 对象表示的文件中写入数据的文件输出流。
* 输出数据:
* public void write(int b):输出一个字节;(b作为编码,输出的是对应的"字符")
* public void write(byte[] b):输出一个字节数组
* public void write(byte[] b,int off,int len):输出一个字节数组的一部分;
* 关闭流:
* close();
public class Demo {public static void main(String[] args) {try {//1.String的构造FileOutputStream out = new FileOutputStream("Demo06_File.txt");//2.File的构造/*File file = new File("C:\\test\\test2.txt");FileOutputStream out2 = new FileOutputStream(file);*///3.输出数据//1).write(int n):输出一个字节out.write(97);//out.write(98);//2).write(byte[] byteArray):输出一个字节数组/*byte[] byteArray = "abcdFFFFFF".getBytes();out.write(byteArray);//3).write(byte[] b,int off,int len):输出一个字节数组的一部分byte[] byteArray2 = "你好5588Java".getBytes();//输出"5588"out.write(byteArray2,4,4);*///3.释放资源:大家以后要养成习惯,用完后,一定要close()关闭流;out.close();//模拟程序正在运行/*while(true){}*/} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}2、IO流_字节流_输出流_输出换行和追加写入
* 1.实现换行:out.write("\r\n".getBytes());
*
* 1.Windows:\r\n
* 2.Linux:\r
* 3.Mac:\n
* 2.实现追加写入:需要FileOutputStream的另外两个构造方法:
* FileOutputStream(String name, boolean append) 创建一个向具有指定 name 的文件中写入数据的输出文件流。
* FileOutputStream(File file, boolean append)创建一个向指定 File 对象表示的文件中写入数据的文件输出流。
public class Demo {public static void main(String[] args) {try {//1.实例化一个输出流对象FileOutputStream out = new FileOutputStream("demo07_File.txt",true);//2.输出数据out.write("第一行".getBytes());out.write("\r\n".getBytes());//输出一个换行out.write("第二行".getBytes());out.write("\r\n".getBytes());//3.释放资源out.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}3、IO流_字节流_输出流_加入异常处理
* 关于异常的处理方式:
* 1.如果在方法内操作文件,可以将全部异常"抛出",由调用方去处理;
* 2.如果在main()方法内,使用try...catch...finally...语句
public class Demo {public static void main(String[] args) {String file = "demo08_File.txt";try {writeToFile(file);} catch (IOException e) {e.printStackTrace();}FileOutputStream out = null;try {out = new FileOutputStream(file);out.write("你好".getBytes());} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally{if(out != null){try {out.close();} catch (IOException e) {e.printStackTrace();}}}}public static void writeToFile(String fileName) throws IOException{FileOutputStream out = new FileOutputStream(fileName);out.write("第一行".getBytes());out.write("\r\n".getBytes());out.write("第二行\r\n".getBytes());out.close();}}4、IO流_字节流_输入流_FileInputStream
* 1.字节流:
* 输出流:OutputStream:
* |--FileOutputStream(类):
* 构造方法:四个(两个带追加写入的)
* 写入方法:三个:
* 输入流:InputStream:
* |--FileInputStream(类):
* 构造方法:一定要确保文件存在,否则抛出异常;
* FileInputStream(File file) :通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的 File 对象 file 指定。
* FileInputStream(String name) :通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的路径名 name 指定。
* 读取的方法:
* public int read():读取一个字节;
* public int read(byte[] b):读取一个字节数组。
* 工作方式:
* 1.如果文件长度够的话,会尽量的填充满byte[]数组b;
* 2.返回值:本次读取的字节数;
* 2.字符流:
* 输出流:Writer
* 输入流:Raeder
public class Demo {public static void main(String[] args) {try {File file = new File("demo09_File.txt");if(!file.exists()){file.createNewFile();}FileInputStream in = new FileInputStream("demo09_File.txt");//FileInputStream in2 = new FileInputStream(file);//一次读取一个字节/*int n = in.read();while(n != -1){System.out.println("读取的字节为:" + n);System.out.println("将字节转换为字符:" + (char)n);n = in.read();}*///常用的写法/*int n = 0;while((n = in.read()) != -1){System.out.println("将字节转换为字符:" + (char)n);}*///一次读取一个字节数组byte[] byteArray = new byte[3];int n = 0;while((n = in.read(byteArray)) != -1){/*System.out.println("n = " + n);System.out.println("读取的字节数组中的内容:" + Arrays.toString(byteArray));System.out.println("读取的字符:");for(byte b : byteArray){System.out.print((char)b + " ");}System.out.println();*///怎样将一个字节数组,转换为一个String:使用String的构造方法String str = new String(byteArray,0,n);System.out.println("从0开始,取:" + n + " 个长度:");System.out.println("读取的内容为:" + str);}in.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}5、IO流_字节流_练习_复制一个文本文件
* 复制文本文件:
* 1.读取:输入流:FileInputStream;
* 2.一次读取一个字节(或者一次读取一个字节数组)
* 3.写入:输出流:FileOutputStreasm:
* 4.一次写入一个字节(或者一次写入一个字节数组)
* 例如:将demo09_File.txt复制一份,名称为:demo10_File.txt
public class Demo {public static void main(String[] args) throws IOException {//1.实例化一个输入流FileInputStream in = new FileInputStream("demo09_File.txt");//2.实例化一个输出流FileOutputStream out = new FileOutputStream("demo10_File.txt");//3.一次读、写一个字节/*int n = 0;while((n = in.read()) != -1){out.write(n);}*///一次读、写一个字节数组byte[] byteArray = new byte[1024];int n = 0;while((n = in.read(byteArray)) != -1){out.write(byteArray, 0, n);}//4.释放资源in.close();out.close();System.out.println("复制完毕!");}}6、IO流_字节流_练习_复制一个图片文件
* 复制图片文件:
* 一次读写一个字节
* 一次读写一个字节数组;
public class Demo {public static void main(String[] args) throws IOException {//1.输入流FileInputStream in = new FileInputStream("C:\\aaa\\哥有老婆.mp4");//2.输出流FileOutputStream out = new FileOutputStream("demo11_哥有老婆_copy2.mp4");//3.一次读写一个字节数组/*int n = 0;while((n = in.read()) != -1){out.write(n);}*/int len = 0;byte[] byteArray = new byte[1024];while((len = in.read(byteArray)) != -1){out.write(byteArray,0,len);}//4.释放资源out.close();in.close();System.out.println("复制完毕");}}7、IO流_字节流_带缓冲的字节流
* 带缓冲的字节流:
* 字节流:
* 输出流:OutputStream:
* |--FileOutputStream(基本流):
* |--FilterOutputStream(没学)
* |--BufferedOutputStream(类--缓冲流)
* 输入流:InputStream:
* |--FileInputStream(基本流):
* |--FilterInputStream(没学)
* |--BufferedInputStream(类--缓冲流)
* 缓冲流:内部只提供了"缓冲区",读取、写入操作仍然需要"基本流"
* BufferedOutputStream:缓冲的输出流:
* 构造方法:
* BufferedOutputStream(OutputStream out): 创建一个新的缓冲输出流,以将数据写入指定的底层输出流。
* 写入的方法:
* (无特有的)都是从父类继承的;三种
* 成员方法:
* flush():刷新缓冲区;
* close();flush() + close()
* BufferedInputStream :缓冲的输入流
* 构造方法:
* BufferedInputStream(InputStream in)
* 读取的方法:
* (无特有的)都是从父类继承的;两种
public class Demo {public static void main(String[] args) throws IOException{//构造一个带缓冲的输出流BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("demo12_File.txt"));out.write("你好哇".getBytes());out.write("\r\n".getBytes());out.write("Java,HelloWorld".getBytes());//out.flush();out.close();//flush() + close();//构造一个带缓冲的输入流:BufferedInputStream in = new BufferedInputStream(new FileInputStream("demo12_File.txt"));//一次读取一个字节/*int n = 0;while((n = in.read()) != -1){System.out.println((char)n);}*///一次读一个字节数组int n = 0;byte[] byteArray = new byte[1024];while((n = in.read(byteArray)) != -1){String str = new String(byteArray,0,n);System.out.println("读取的内容:" + str);}in.close();}}8、IO流_练习_四种方式复制视频文件
* 基本流:
* FileInputStream:
* FileOutputStream:
* 一次读写一个字节: method1()
* 一次读写一个字节数组:method2()
* 缓冲流:
* BufferedInputStream:
* BufferedOutputStream:
* 一次读写一个字节; method3()
* 一次读写一个字节数组:method4()
public class Demo {public static void main(String[] args) throws IOException {long start = System.currentTimeMillis();//method1();//55890 毫秒!//method2();//执行时间:81 毫秒!//method3();//执行时间:681 毫秒!method4();//执行时间:41 毫秒!long end = System.currentTimeMillis();System.out.println("执行时间:" + (end - start) + " 毫秒!");}//基本流,一次读写一个字节private static void method1() throws IOException {FileInputStream in = new FileInputStream("C:\\aaa\\哥有老婆.mp4");FileOutputStream out = new FileOutputStream("demo13_copy_method1.mp4");//一次读写一个字节int n = 0;while((n = in.read()) != -1){out.write(n);}out.close();in.close();}//基本流,一次读写一个字节数组private static void method2() throws IOException {FileInputStream in = new FileInputStream("C:\\aaa\\哥有老婆.mp4");FileOutputStream out = new FileOutputStream("demo13_copy_method2.mp4");//一次读写一个字节int n = 0;byte[] byteArray = new byte[1024];while((n = in.read(byteArray)) != -1){out.write(byteArray,0,n);}out.close();in.close();}//缓冲流,一次读写一个字节private static void method3() throws IOException{BufferedInputStream in = new BufferedInputStream(new FileInputStream("C:\\aaa\\哥有老婆.mp4"));BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("demo13_copy_method3.mp4"));//一次读写一个字节int n = 0;while((n = in.read()) != -1){out.write(n);}out.close();in.close();}//缓冲流,一次读写一个字节数组private static void method4() throws IOException{BufferedInputStream in = new BufferedInputStream(new FileInputStream("C:\\aaa\\哥有老婆.mp4"));BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("demo13_copy_method4.mp4"));//一次读写一个字节int n = 0;byte[] byteArray = new byte[1024];while((n = in.read(byteArray)) != -1){out.write(byteArray,0,n);}out.close();in.close();}}二、String类编码_解码的方式
* 编码:就是把看得懂的,变为看不懂的;
* getBytes();
* "你好".getBytes();
* 解码:
* String的构造方法
*
* 大家在以后写程序时,凡是涉及到"文件的读写"时,有必要显示的指定"编码方式"和"解码方式"
* 这样有助于后期维护。
编码表概述和常见的编码表
计算机只能识别二进制数据,早期由来是电信号。
为了方便应用计算机,让它可以识别各个国家的文字。
就将各个国家的文字用数字来表示,并一一对应,形成一张表。
ASCII:美国标准信息交换码。
用一个字节的7位可以表示。
ISO8859-1:拉丁码表。欧洲码表
用一个字节的8位表示。
GB2312:中国的中文编码表。
GBK:中国的中文编码表升级,融合了更多的中文文字符号。
GB18030:GBK的取代版本
BIG-5码 :通行于台湾、香港地区的一个繁体字编码方案,俗称“大五码”。
Unicode:国际标准码,融合了多种文字。
所有文字都用两个字节来表示,Java语言使用的就是unicode
UTF-8:最多用三个字节来表示一个字符。
UTF-8不同,它定义了一种“区间规则”,这种规则可以和ASCII编码保持最大程度的兼容:
它将Unicode编码为00000000-0000007F的字符,用单个字节来表示
它将Unicode编码为00000080-000007FF的字符用两个字节表示
它将Unicode编码为00000800-0000FFFF的字符用3字节表示
public class Demo {public static void main(String[] args) throws UnsupportedEncodingException {//byte[] byteArray = "你好".getBytes();//编码,使用GBK码表byte[] byteArray = "你好".getBytes("GBK");//...写入到文件....//从文件读取,一次读取一个字节数组byte[] inByteArray = byteArray;//解码//String str = new String(inByteArray);//解码:使用GBK解码String str = new String(inByteArray,"GBK");System.out.println(str);}}
三、转换流
1、转换流_OutputStreamWriter
* 转换流:可以将一个"字节流",转换为"字符流":
* OutputStreamWriter: 是字符流通向字节流的桥梁
* InputStreamReader: 是字节流通向字符流的桥梁
* 字符流:
* 输出流:Writer
* |--OutputStreamWriter:
* 构造方法:
* OutputStreamWriter(OutputStream out) 创建使用默认字符编码的 OutputStreamWriter。
* 输出的方法:
* public void write(int c):输出一个字符
* public void write(char[] cbuf):输出一个字符数组
* public void write(char[] cbuf,int off,int len):输出一个字符数组的一部分
* public void write(String str):输出一个字符串
* public void write(String str,int off,int len):输出一个字符串的一部分
刷新:
flush();
关闭:
close():flush() + close();
* 输入流:Reader
* |--InputStreamReader:
public class Demo {public static void main(String[] args) throws IOException {OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("demo15_File.txt"));//out.write(97);char[] charArray = {'a','b','你','好'};out.write(charArray);out.write(charArray,2,2);out.write("\r\n终于可以输出一个字符串了\r\n");String str = "我爱Java,我爱祖国!";out.write(str,7,4);out.close();}}2、转换流_InputStreamReader
* InputStreamReader:
* 构造方法:
* InputStreamReader(InputStream in) 创建一个使用默认字符集的 InputStreamReader。
* 读取的方法:
* public int read():读取一个字符
* public int read(char[] cbuf):读取一个字符数组
public class Demo {public static void main(String[] args) throws IOException{InputStreamReader in = new InputStreamReader(new FileInputStream("demo16_File.txt"));//一次读取一个字符/*int n = 0;while((n = in.read()) != -1){System.out.println("读取的int值:" + n);System.out.println("读取的字符:" + (char)n);}*///一次读取一个字符数组int n = 0;char[] charArray = new char[6];while((n = in.read(charArray)) != -1){String str = new String(charArray,0,n);System.out.println("读取的内容:" + str);}in.close();}}3、字符流_FileWriter_FileReader
* 1.字节流:
* 输出流:OutputStream:(三个写的方法)
* |--FileOutputStream:
* |--FilterOutputSteam(不讲):
* |--BufferedOutputStream:
* 输入流:InputStream:
* |--FileInputStream:
* |--FilterInputStream(不讲):
* |--BufferedInputStream:
* 2.字符流:
* 输出流:Writer:(五个写的方法)
* |--OutputStreamWriter(转换流):
* |--FileWriter(字符流):
* 构造方法:
* FileWriter(File file) : 根据给定的 File 对象构造一个 FileWriter 对象。
* FileWriter(File file, boolean append) 根据给定的 File 对象构造一个 FileWriter 对象。
* FileWriter(String fileName) 根据给定的文件名构造一个 FileWriter 对象。
* FileWriter(String fileName, boolean append) 根据给定的文件名以及指示是否附加写入数据的 boolean 值来构造 FileWriter 对象。
写入的方法:
(无特有的)
*
* 输入流:Reader:(两个读取的方法)
* |--InputStreamReader(转换流):
* |--FileReader(字符流):
* 构造方法:
* FileReader(File file) :在给定从中读取数据的 File 的情况下创建一个新 FileReader。
* FileReader(String fileName) 在给定从中读取数据的文件名的情况下创建一个新 FileReader。
* 读取的方法:
* (无特有的)
public class Demo {public static void main(String[] args) throws IOException{FileReader in = new FileReader("demo16_File.txt");FileWriter out = new FileWriter("demo17_File_copy_2.txt");//一次读写一个字符/*int n = 0;while((n = in.read()) != -1){out.write(n);}*///一次读写一个字符数组int n = 0;char[] charArray = new char[1024];while((n = in.read(charArray)) != -1){out.write(charArray,0,n);}//释放资源out.close();in.close();}}4、字符流_缓冲流_BufferedWriter_BufferedReader
* 字符流:
* 输出流:Writer:(五个写入的方法):1.输出一个字符,一个字符数组,一个字符数组的一部分,一个字符串,一个字符串的一部分;
* |--OutputStreamWriter:
* |--FileWriter:
* |--BufferedWriter:
* 构造方法:
* BufferedWriter(Writer out)
* 写入的方法:
* (无特有的)
* 成员方法:
* newLine():输出一个换行符;效果同:\r\n的作用
*
* 输入流:Reader:(两个读取的方法):1.读取一个字符;2.读取一个字符数组
* |--InputStreamReader:
* |--FileReader:
* |--BufferedReader:
* 构造方法:
* BufferedReader(Reader in)
* 读取的方法:
* readLine():读取一行数据;
public class Demo {public static void main(String[] args) throws IOException{BufferedReader in = new BufferedReader(new FileReader("demo17_File_copy.txt"));String s = null;while((s = in.readLine()) != null){System.out.println(s);}}}5、练习_字符流_读写文件的五种方式
* 字符流读写文件的五种方式:
* FileReader:
* FileWriter:
* 一次读写一个字符; method1();
* 一次读写一个字符数组;method2();
* BufferedReader:
* BufferedWriter:
* 一次读写一个字符 method3();
* 一次读写一个字符数组:method4();
* 一次读写一行; method5();
public class Demo {public static void main(String[] args) throws IOException{//method1();//method2();//method3();//method4();method5();System.out.println("复制完毕!");}//基本字符流,一次读写一个字符private static void method1() throws IOException {FileReader in = new FileReader("demo10_File.txt");FileWriter out = new FileWriter("demo19_method1.txt");//一次读写一个字符int n = 0;while((n = in.read()) != -1){out.write(n);}in.close();out.close();}//基本字符流,一次读写一个字符数组private static void method2() throws IOException {FileReader in = new FileReader("demo10_File.txt");FileWriter out = new FileWriter("demo19_method2.txt");// 一次读写一个字符int n = 0;char[] charArray = new char[1024];while((n = in.read(charArray)) != -1){out.write(charArray,0,n);}in.close();out.close();}//缓冲流,一次读写一个字符private static void method3() throws IOException {BufferedReader in = new BufferedReader(new FileReader("demo10_File.txt"));BufferedWriter out = new BufferedWriter(new FileWriter("demo19_method3.txt"));//一次读写一个字符int n = 0;while((n = in.read()) != -1){out.write(n);}in.close();out.close();}//缓冲流,一次读写一个字符数组private static void method4() throws IOException {BufferedReader in = new BufferedReader(new FileReader("demo10_File.txt"));BufferedWriter out = new BufferedWriter(new FileWriter("demo19_method4.txt"));//一次读写一个字符int n = 0;char[] charArray = new char[1024];while((n = in.read(charArray)) != -1){out.write(charArray,0,n);}in.close();out.close();}//缓冲流,一次读写一行private static void method5() throws IOException {BufferedReader in = new BufferedReader(new FileReader("demo10_File.txt"));BufferedWriter out = new BufferedWriter(new FileWriter("demo19_method5.txt"));String row = null;while((row = in.readLine()) != null){out.write(row);out.newLine();}in.close();out.close();}}四、其他流
1、数据操作流_DataInputStream_DataOutputStream
* InputStream:
* |--FilterInputStream:
* |--java.io.DataInputStream:能够读取Java的基本数据类型:
* OutputStream:
* |--FilterOutputStream:
* |--java.io.DataOutputStream:能够写入Java的基本数据类型;
public class Demo {public static void main(String[] args) throws IOException {write();read();}public static void write() throws IOException{DataOutputStream out = new DataOutputStream(new FileOutputStream("demo01.txt"));out.writeByte(127);out.writeShort(128);out.writeChar(97);out.writeInt(2000);out.writeLong(8000);out.writeFloat(3.0F);out.writeDouble(4.0);out.close();System.out.println("写入完毕!");}public static void read() throws IOException{DataInputStream in = new DataInputStream(new FileInputStream("demo01.txt"));byte v1 = in.readByte();short v2 = in.readShort();char v3 = in.readChar();//int v4 = in.read();//虽然read()方法也返回int,但不要用这个,这个是父类中读取的方法;int v4 = in.readInt();long v5 = in.readLong();float v6 = in.readFloat();double v7 = in.readDouble();in.close();System.out.println("v1 = " + v1);System.out.println("v2 = " + v2);System.out.println("v3 = " + v3);System.out.println("v4 = " + v4);System.out.println("v5 = " + v5);System.out.println("v6 = " + v6);System.out.println("v7 = " + v7);}}2、字节缓冲流_ByteArrayOutputStream_ByteArrayInputStream
* java.io.ByteArrayOutputStream:向缓存区输出一个byte[]数组;
* java.io.ByteArrayInputStream:从缓存区读取byte[]数组的内容;
public class Demo {public static void main(String[] args) throws IOException {ByteArrayOutputStream byteOut = new ByteArrayOutputStream();FileInputStream in = new FileInputStream("demo02.txt");//一次读取一个字节数组int n = 0;byte[] byteArray = new byte[3];while((n = in.read(byteArray)) != -1){//以前我们这里要么转换为字符串输出;要么写入到另一个文件//现在,我们什么都不做,先将已读取的字节数组缓存起来byteOut.write(byteArray, 0, n);}in.close();//从缓冲区读取byte[]数组ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());//一次读取一个字节,或者一个字节数组,或者直接转换为一个字符串String str = new String(byteOut.toByteArray());System.out.println(str);//一次读取一个字节,写入到另一个文件FileOutputStream fileOut = new FileOutputStream("demo02_copy.txt");n = 0;while((n = byteIn.read()) != -1){fileOut.write(n);}fileOut.close();System.out.println("写入完毕!");}}3、打印流_PrintStream_PrintWriter
* 打印流:
* 1.字节打印流:PrintStream:
* 2.字符打印流:PrintWriter:字符流(输出流)
* 打印流特点
* 1.只能操作目的地,不能操作数据。(只能写出,没有读取)
* 2.可以操作任意类型的数据。
* 3.如果启动了自动刷新,能够自动刷新。
* 4.可以操作文件的流
* 一.PrintWriter:
* 1).如果启动自动刷新,只有在println、printf 或 format 的其中一个方法时才可能完成此操作
public class Demo {public static void main(String[] args) throws IOException {PrintWriter out = new PrintWriter(new FileWriter("demo03_PrintWriter.txt"),true);//out.write("你好Java");//out.write("HelloWorld");out.println("你好Java");//write() + newLine() + flush()out.println("HelloWorld");out.close();}}4、练习_打印流复制文本文件
* 打印流复制文本文件:
* 1.打印流只有输出流:PrintWriter
* 2.输入流:BufferedReader
public class Demo {public static void main(String[] args) throws IOException {BufferedReader in = new BufferedReader(new FileReader("demo05.txt"));PrintWriter out = new PrintWriter(new FileWriter("demo05_copy.txt"),true);//一次读取一行数据String row = null;while(( row = in.readLine()) != null){out.println(row);//write() + newLine() + flush()}out.close();in.close();}}5、打印流_PrintStream_输出语句的本质
* 打印流:
* 1.字节流:PrintStream:System.out类型
* 2.字符流:PrintWriter:
public class Demo {public static void main(String[] args) {System.out.println("你好");PrintStream ps = System.out;ps.println("HelloWorld");int[] intArray = {1,2,3,4};System.out.println(intArray);//地址char[] charArray = {'a','b','c'};System.out.println(charArray);//println(char[] c);}}6、标准输入流_三种方式实现键盘录入
* 三种方式实现键盘录入:
* 1.Scanner:
* 2.main()方法的形参;
* 3.System.in;
* 标准的输出流:System.out
public class Demo {public static void main(String[] args) throws IOException {InputStream in = System.in;/* * int n = in.read(); System.out.println("你输入的字节数:" + n); * System.out.println("转换为字符:" + (char)n); */// 想办法从控制台读取一行数据:// 读取一行数据:BufferedReader// 从字节流--->转换流--->字符流/* * InputStreamReader isr = new InputStreamReader(in); BufferedReader * bufIn = new BufferedReader(isr); */BufferedReader bufIn = new BufferedReader(new InputStreamReader(System.in));String row = bufIn.readLine();System.out.println("你输入的内容是:" + row);//将标准的输出流也封装为带缓冲的字符流PrintStream ps = System.out;BufferedWriter bufOut = new BufferedWriter(new OutputStreamWriter(ps));bufOut.write("张学友");bufOut.newLine();bufOut.write("刘德华");bufOut.newLine();bufOut.close();}}
7、随机访问流_RandomAccessFile类
* java.io.RandomAccessFile(类):
* 构造方法:
* RandomAccessFile(File file, String mode) 创建从中读取和向其中写入(可选)的随机访问文件流,该文件由 File 参数指定。
* RandomAccessFile(String name, String mode) 创建从中读取和向其中写入(可选)的随机访问文件流,该文件具有指定名称。
* mode:
* "r" 以只读方式打开。调用结果对象的任何 write 方法都将导致抛出 IOException。
* "rw" 打开以便读取和写入。如果该文件尚不存在,则尝试创建该文件。
* 成员方法:
* 1.获取文件指针:
* getFilePointer():获取当前的文件指针
* seek():设置当前文件指针;
public class Demo {public static void main(String[] args) throws IOException {//write();read();}private static void read() throws IOException {RandomAccessFile in = new RandomAccessFile("demo07.txt","r");System.out.println("文件指针位置:" + in.getFilePointer());int v1 = in.readInt();System.out.println("读取int后,指针位置:" + in.getFilePointer());boolean v2 = in.readBoolean();System.out.println("读取boolean后,指针位置:" + in.getFilePointer());short v3 = in.readShort();System.out.println("读取short后,指针位置:" + in.getFilePointer());String v4 = in.readUTF();System.out.println("读取UTF后,指针位置:" + in.getFilePointer());//将指针移到boolean位置,重新读取boolean值in.seek(4);boolean v5 = in.readBoolean();in.close();System.out.println("v1 = " + v1);System.out.println("v2 = " + v2);System.out.println("v3 = " + v3);System.out.println("v4 = " + v4);System.out.println("v5 = " + v5);}private static void write() throws IOException {RandomAccessFile out = new RandomAccessFile("demo07.txt","rw");out.writeInt(120);out.writeBoolean(true);out.writeShort(20);out.writeUTF("你好");out.close();System.out.println("写入完毕!");}}8、序列化流_ObjectOutputStream_ObjectInputStream
* 序列化流:
* 1.序列化:可以将一些数据存储到磁盘上,或者通过网络传输到另一台计算器;
* 2.Java中提供了两种流,可以将一个"对象(包括内部属性的值)"存在磁盘上,
* 或者通过网络传输到另一台计算机,这个过程叫:序列化;
* 将一个已被序列化的对象,从硬盘或者网络读取到程序中,这个过程叫:反序列化
* 3.序列化:ObjectOutputStream:
* 注意:当某个对象需要被"序列化"时,此类,必须实现:java.io.Serializable接口
* 反序列化:ObjectInputStream:
* 4.关于类的序列号:
* 1).建议:在类实现了Serializable接口之后,定义:版本号变量(不是必须的)
class Student implements Serializable{private static final long serialVersionUID = 1L;String name;transient int age;//不需要被序列化char sex;String address;}public class Demo {public static void main(String[] args) throws IOException, ClassNotFoundException {Student stu = new Student();stu.name = "刘德华";stu.age = 20;//构造一个"序列化"流ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("demo08.txt"));out.writeObject(stu);out.close();//反序列化ObjectInputStream in = new ObjectInputStream(new FileInputStream("demo08.txt"));Object obj = in.readObject();//从文件读取对象信息,并在内存中创建这个对象空间System.out.println("obj = " + obj);Student stu2 = (Student)obj;System.out.println(stu2.name + "," + stu2.age);//System.out.println("stu == stu2 : " + (stu == stu2));//falseSystem.out.println("程序结束!");}}
9、Properties类_作为Map的基本功能
* java.util.Properties类:
* Hashtable
* |--Properties:
* 1.Properties类属于一个Map类型的集合;
* 2.它的特有功能是:可以将自己内部的属性集,映射到文件中。可以和IO流结合,读取和写入配置文件中的内容;
* 3.配置文件:
* 软件在运行时,都需要记录一些运行时的一些信息,或者用户的配置信息,程序可以将这些信息记录到一个
* 文本文件中;当再次启动时,可以先读取用户配置信息,启动后,根据用户的以往的设置,为用户展示程序界面;
* 4.既然Properties是一个Map集合,我们先把它当做一个集合来操作;
* 5.特殊功能:
* String getProperty(String key);-->get()
* void setProperty(String key,String value):-->put()
* Set<String> stringPropertyNames()-->keySet()
public class Demo {public static void main(String[] args) {Properties pro = new Properties();/*pro.put("it001", "张三");pro.put("it002", "李四");pro.put("it003", "王五");Set keySet = pro.keySet();for(Object obj : keySet){System.out.println(obj + "--" + pro.get(obj));}*///特有方法测试pro.setProperty("it001", "张三");//--->put()pro.setProperty("it002", "李四");pro.setProperty("it003", "王五");//System.out.println(pro.getProperty("it001"));//--->get()//遍历Set<String> keys = pro.stringPropertyNames();for(String key : keys){System.out.println(key + "--" + pro.getProperty(key));}}}
10、Properties类_操作配置文件
* Properties和IO流的结合使用
* public void load(Reader reader):从配置文件中读取内容,并填充本集合
* public void store(Writer writer,String comments):将本集合中的内容写入到配置文件;
public class Demo {
public static void main(String[] args) throws IOException {
Properties pro = new Properties();
//**************写入数据**************//
//1.填充集合
/*pro.setProperty("金币", "200000");
pro.setProperty("钻石", "1000");
pro.setProperty("疲劳", "200");
pro.setProperty("活跃度", "100");
//2.准备一个字符流(输出流)
BufferedWriter out = new BufferedWriter(new FileWriter("game.properties"));
//3.调用Properties的store()方法,将集合中的数据写入到配置文件
pro.store(out, "游戏配置文件");
out.close();
System.out.println("写入完毕");*/
//*************读取数据*******************//
Properties inPro = new Properties();
//1.准备一个输入流
FileReader fileIn = new FileReader("game.properties");
//2.调用load()方法读取配置文件信息
inPro.load(fileIn);
//3.关闭文件流
fileIn.close();
//4.遍历集合
Set<String> keys = inPro.stringPropertyNames();
for(String key : keys){
System.out.println(key + "---" + inPro.getProperty(key));
}
}
}
11、Properties类_判断文件中是否有指定的键如果有就修改值的案
* 判断文件中是否有指定的键如果有就修改值的案例
* 将"疲劳值"修改为:250
public class Demo {public static void main(String[] args) throws IOException {Properties pro = new Properties();//1.准备一个输入流FileReader fileIn = new FileReader("game.properties");//2.调用load()方法读取配置文件pro.load(fileIn);//3.关闭文件流fileIn.close();//4.遍历集合Set<String> keys = pro.stringPropertyNames();for(String key : keys){if(key.equals("疲劳")){pro.setProperty("疲劳", "250");break;}}//写入配置文件//1.准备一个输出流FileWriter out = new FileWriter("game.properties");pro.store(out, null);out.close();System.out.println("操作完毕!");}}12、NIO的介绍和JDK7下NIO的一个案例
* NIO的介绍和JDK7下NIO的一个案例:
*
* Path:与平台无关的路径。
* Paths:包含了返回Path的静态方法。
public static Path get(URI uri):根据给定的URI来确定文件路径。
Files:操作文件的工具类。提供了大量的方法,简单了解如下方法
public static long copy(Path source, OutputStream out) :复制文件
public static Path write(Path path, Iterable<? extends CharSequence> lines, Charset cs, OpenOption... options):
* 把集合的数据写到文件。
public class Demo {public static void main(String[] args) throws FileNotFoundException, IOException {//1.public static long copy(Path source, OutputStream out)//复制一个文件:从C:\\vcredist_x86.log到项目根目录下Files.copy(Paths.get("C:\\vcredist_x86.log"), new FileOutputStream("vcredist_x86_copy.log"));System.out.println("复制完毕");//2.public static Path write(Path path, Iterable<? extends CharSequence> lines, Charset cs, OpenOption... options):ArrayList<String> strList = new ArrayList<>();strList.add("刘德华");strList.add("张学友");strList.add("郭富城");strList.add("黎明");Files.write(Paths.get("demo12_List.txt"), strList, Charset.forName("GBK"));System.out.println("写入完毕!");}}五、练习
1、练习_把集合中的数据存储到文本文件案例
* 把集合中的数据存储到文本文件案例
* 1.向文本写入:字符输出流;BufferedWriter
public class Demo {public static void main(String[] args) throws IOException {ArrayList<String> strList = new ArrayList<>();strList.add("刘德华");strList.add("张学友");strList.add("刘亦菲");strList.add("马德华");BufferedWriter out = new BufferedWriter(new FileWriter("demo13.txt"));//遍历集合for(String s : strList){out.write(s);out.newLine();}//释放资源out.close();System.out.println("写入完毕!");}}2、练习_把文本文件中的数据存储到集合中案例
* 把文本文件中的数据存储到集合中案例
* 1.先准备一个集合对象;
* 2.从文本文件读取数据:BufferedReader
public class Demo {public static void main(String[] args) throws IOException {ArrayList<String> strList = new ArrayList<>();BufferedReader in = new BufferedReader(new FileReader("demo13.txt"));String row = null;while((row = in.readLine()) != null){strList.add(row);}in.close();//遍历集合for(String s : strList){System.out.println(s);}}}3、练习_随机获取文本文件中的姓名案例
* 随机获取文本文件中的姓名案例
* 1.先读取文件中的所有人员;
* 2.将这些人员存储到一个List中;
* 3.生成一个0到集合最大索引的一个随机数,作为索引,到集合中,将此元素取出;
public class Demo {public static void main(String[] args) throws IOException {ArrayList<String> strList = new ArrayList<>();BufferedReader in = new BufferedReader(new FileReader("demo13.txt"));String row = null;while((row = in.readLine()) != null){strList.add(row);}in.close();//生成随机索引Random rdm = new Random();int index = rdm.nextInt(strList.size());System.out.println("随机人员:" + strList.get(index));}}4、练习_复制单级文件夹案例
* 复制单级文件夹案例
* 1.封装初始目录:File
* 2.封装目标目录:File
* 3.判断目标目录是否存在,如果不存在,则创建;
* 4.遍历初始目录下的所有文件:
* 针对每个文件,建立"输入","输出"流
* 因为文件不一定是什么类型,所以:可以使用"字节流"
public class Demo {public static void main(String[] args) throws IOException {File srcFile = new File("C:\\aaa");File destFile = new File("C:\\aaa_copy\\");if(!destFile.exists()){destFile.mkdir();}//获取原目录下的所有文件File[] fileArray = srcFile.listFiles();for(File f : fileArray){//建立输入、输出流BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(destFile,f.getName())));//new File("C:\\aaa_copy","1.mp4")//一次读写一个字节数组int n = 0;byte[] byteArray = new byte[1024];while((n = in.read(byteArray)) != -1){out.write(byteArray,0,n);}out.close();in.close();}System.out.println("复制完毕!");}}5、练习_复制指定目录下指定后缀名的文件并修改名称案例
* 复制指定目录下指定后缀名的文件并修改名称案例
* 将C:\\20150822\\目录下的所有.java文件,复制到C:\\java_copy\\目录下,
* 并将文件重命名为:原文件名_毫秒值.txt
*
* 1.封装初始目录:File
* 2.封装目标目标:File
* 3.获取初始目录下的所有文件和目录:listFiles
* 4.遍历数组,获取每一个File;
* 5.验证File是否是文件,并且是.java结尾:
* 是:复制;
* 否:验证是否是目录:
* 是:回到3
public class Demo {public static void main(String[] args) throws IOException {File srcFile = new File("C:\\20150822");File destFile = new File("C:\\20150822_java_copy\\");if(!destFile.exists()){destFile.mkdir();}listFile(srcFile,destFile);System.out.println("全部复制完毕!");}private static void listFile(File srcFile, File destFile) throws IOException {if(srcFile == null || destFile == null){return ;}//获取原目录下的所有文件和目录File[] fileArray = srcFile.listFiles();if(fileArray != null){for(File file : fileArray){if(file.isFile() && file.getName().endsWith(".java")){//复制BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(destFile,file.getName() + "_" + new Date().getTime() + ".txt")));int n = 0;byte[] byteArray = new byte[1024];while((n = in.read(byteArray)) != -1){out.write(byteArray,0,n);}out.close();in.close();System.out.println(file.getAbsolutePath() + " 复制完毕!");}else if(file.isDirectory()){listFile(file,destFile);}}}}}总结:
三.IO流:
1.字节流:
1).输出流:OutputStream:写入的方法:三种:写入一个字节;写入一个字节数组;写入一个字节数组的一部分
|--FileOutputStream:
|--FilterOutputStream(不学):
|--BufferedOutputStream
2).输入流:InputStream:读取的方法:两种:读取一个字节;读取一个字节数组;
|--FileInputStream:
|--FilterInputStream(不学):
|--BufferedInputStream:
2.字符流:
1).输出流:Writer:写入的方法:五种:写入一个字符;写入一个字符数组;写入一个字符数组的一部分;写入一个字符串;写入一个字符串的一部分
|--OutputStreamWriter(转换流):是字符流通向字节流的桥梁
|-FileWriter:
|--BufferedWriter:
newLine():输出一个换行符;
2).输入流:Reader:读取的方法:两种:读取一个字符;读取一个字符数组;
|--InputStreamReader(转换流):是字节流通向字符流的桥梁
|--FileReader:
|--BufferedReader:
readLine():读取一行数据;
3.数据输入输出流:可以读写Java中基本数据类型,当写入文本时,是按各种数据类型相应的字节数写入的;
DataInputStream:
DataOutputStream:
4..内存操作流(byte[]数组的缓存区流):它类似于StringBuffer
ByteArrayOutputStream:
ByteArrayInputStream:
5.打印流:
1.分类:
1).字节流:PrintStream:(System.out)
2).字符流:PrintWriter:
2.特点:
1).只能操作目的地,不能操作数据。
2).可以操作任意类型的数据。
3).如果启动了自动刷新,能够自动刷新。
4).可以操作文件的流
6.三种方式实现接收控制台数据:
1.Scanner:
2.main()方法形参;
3.System.in: System.in --> 转换流 --> 带缓冲的字符流
7.随机访问流:
RandomAccessFile:
1).获取文件指针:getFilePointer();
2).设置文件指针:seek();
8.序列化流:
1.序列化流:ObjectOutputStream:
2.反序列化流:ObjectInputStream:
3.注意:需要被序列化的类,必须实现接口:Serializable
4.为了控制版本号,建议定义成员变量:serialVersionUID设定版本号;
5.使用transient关键字声明不需要序列化的成员变量;
9.Properties类:
1.它本质上是一个Map集合,直接继承自:Hashtable;
2.它结合IO流,可以读写配置文件中的属性信息;
3.读取配置文件:load(Readerreader):
4.写入配置文件:store(Writerout,String str):
10.JDK7的NIO:
Path:与平台无关的路径。
Paths:包含了返回Path的静态方法。
publicstatic Path get(URI uri):根据给定的URI来确定文件路径。
Files:操作文件的工具类。提供了大量的方法,简单了解如下方法
publicstatic long copy(Path source, OutputStream out) :复制文件
publicstatic Path write(Path path, Iterable<? extends CharSequence> lines,Charset cs, OpenOption... options):
把集合的数据写到文件。
///////////////////////////////////////////////////////////////////////
一.数据输入输出流:可以读写Java中基本数据类型,当写入文本时,是按各种数据类型相应的字节数写入的;
DataInputStream:
DataOutputStream:
二.内存操作流(byte[]数组的缓存区流):它类似于StringBuffer
ByteArrayOutputStream:
ByteArrayInputStream:
三.打印流:
1.分类:
1).字节流:PrintStream:(System.out)
2).字符流:PrintWriter:
2.特点:
1).只能操作目的地,不能操作数据。
2).可以操作任意类型的数据。
3).如果启动了自动刷新,能够自动刷新。
4).可以操作文件的流
四.三种方式实现接收控制台数据:
1.Scanner:
2.main()方法形参;
3.System.in: System.in --> 转换流 --> 带缓冲的字符流
五.随机访问流:
RandomAccessFile:
1).获取文件指针:getFilePointer();
2).设置文件指针:seek();
六.序列化流:
1.序列化流:ObjectOutputStream:
2.反序列化流:ObjectInputStream:
3.注意:需要被序列化的类,必须实现接口:Serializable
4.为了控制版本号,建议定义成员变量:serialVersionUID设定版本号;
5.使用transient关键字声明不需要序列化的成员变量;
七.Properties类:
1.它本质上是一个Map集合,直接继承自:Hashtable;
2.它结合IO流,可以读写配置文件中的属性信息;
3.读取配置文件:load(Readerreader):
4.写入配置文件:store(Writerout,String str):
八.JDK7的NIO:
Path:与平台无关的路径。
Paths:包含了返回Path的静态方法。
public static Path get(URI uri):根据给定的URI来确定文件路径。
Files:操作文件的工具类。提供了大量的方法,简单了解如下方法
public static long copy(Path source,OutputStream out) :复制文件
public static Path write(Path path,Iterable<? extends CharSequence> lines, Charset cs,OpenOption... options):
把集合的数据写到文件。
- 黑马程序员——Java基础---IO(输入输出)(下)
- 黑马程序员——Java基础---IO(输入输出)(上)
- 黑马程序员——java基础---IO(下)
- 黑马程序员——JAVA IO输入输出(一)
- 黑马程序员——JAVA IO输入输出(三)
- 黑马程序员——JAVA IO输入输出(二)
- 黑马程序员——JAVA IO输入输出(一)
- 黑马程序员——JAVA IO输入输出(二)
- 黑马程序员--Java之IO(输入输出)(下)04
- 黑马程序员-----java基础(IO下)
- 黑马程序员————java基础--------IO输入输出之异常、File类和递归
- 黑马程序员————java基础---------IO输入输出之字节流
- 黑马程序员——Java基础->IO流(下)
- 黑马程序员-java基础之文件输入输出(IO)(当前工程目录下)以及Collections的常用方法
- 黑马程序员——IO/输入输出
- 黑马程序员—IO输入输出流
- 黑马程序员——Java基础---IO
- 黑马程序员——java基础--IO
- HDU2201 简单概率
- SSH 使用原生HTML select
- 电信免费手机卡iFree黄金版使用须知(一)
- NSData转NSString的问题
- Excel中的“定时器”
- 黑马程序员——Java基础---IO(输入输出)(下)
- 关于HIVE数据仓库的基本操作
- strcpy strcmp strcat 函数原型
- google支付接口被刷以及解决方案
- mysqldump: Couldn't execute 'SET OPTION SQL_QUOTE_SHOW_CREATE=1'
- 【c#笔记】网页数据抓取
- SpringMVC Ajax例子
- 我的职业观
- Asoc dapm(一) - kcontrol