黑马程序员—IO流
来源:互联网 发布:房租占收入比例 知乎 编辑:程序博客网 时间:2024/04/19 15:07
——Java培训、Android培训、iOS培训、.Net培训、期待与您交流! ——-
1.IO流概述:
1.1 IO流:IO流:用来处理设备之间的数据传输。
Java对数据的操作是通过流的方式,
用于操作流的对象都在IO包中。
流按操作数据分为两种:字节流和字符流。
(字符流是基于字节流的。)
按流向分为:输入流,输出流。
字节流的抽象基类:InputStream,OutputStream。
字符流的抽象基类:Reader,Writer。
IO流是用于操作数据的,数据最常见的体现形式:文件。
先以操作文件为主演示。
需求:在硬盘上创建一个文件并写入一些文字数据。
找到一个专门用于操作文件的Writer子类对象,FileWriter。
后缀名是父类名,前椎名是该流对象的功能。
2. 字节流与字符流:
由来:
字节流是由字节组成的,字符流是由字符组成的。
字节流是最基本的,所有的InputStrem和OutputStream的子类都是,主要用在处理二进制数据,它是按字节来处理的。
但实际中很多的数据是文本,所以又提出了字符流的概念。
3.字符流缓冲区:
为什么需要引入缓冲区?
提高了流的读写效率,所以在缓冲区创建前,要先创建流对象,也就是先将流对象初始化到构造函数中。
缓冲区原理是什么?
对象中封装数组,将数据存入,再一次性取出。
3.1:BufferedReader(字符读取流缓冲区)
该缓冲区提供了一个一次读一行的方法readLine(),
方便于对文本数据的获取。
当返回null时,表示读到文件末尾。
演示代码:
import java.io.*;class BufferedReaderDemo{ public static void main(String[] args) { FileReader fr = null; BufferedReader bur = null; try { fr = new FileReader("RuntimeDemo.java"); bur = new BufferedReader(fr); String line = null; while ((line = bur.readLine())!=null) { System.out.println(line); } } catch (IOException e) { throw new RuntimeException("读写失败"); } finally { try { if(bur!=null); bur.close(); } catch (IOException e) { throw new RuntimeException("读写失败"); } } } }
自定义BufferedReader演示代码:
import java.io.*;class MyBufferedReader{ private FileReader r; MyBufferedReader(FileReader r) { this.r = r; } public String myReadLine()throws IOException { StringBuilder sb = new StringBuilder(); int ch = 0; while ((ch=r.read())!=-1) { if(ch=='\r') continue; if(ch=='\n') return sb.toString(); else sb.append((char)ch); } if(sb.length()!=0) return sb.toString(); return null; } public void myClose()throws IOException { r.close(); }}class MyBufferedReaderDemo { public static void main(String[] args)throws IOException { FileReader fr = new FileReader("buf.txt"); MyBufferedReader myBuf = new MyBufferedReader(fr); String line=null; while ((line=myBuf.myReadLine())!=null) { System.out.println(line); } myBuf.myClose(); }}
3.2:BufferedWriter(字符输出流缓冲区)
演示代码:
mport java.io.*;class BufferedWriterDemo{ public static void main(String[] args)throws IOException { FileWriter fw = new FileWriter("CCTV.txt"); BufferedWriter buffw = new BufferedWriter(fw); for (int x=1;x<11;x++ ) { buffw.write("CCTV"+x+"套"); buffw.newLine(); buffw.flush(); //写一次刷一次,以防停电电脑关机后内存里的资源释放导致书写内容丢失 } buffw.close(); }}
小练习:
需求:通过缓冲区复制一个.java文件。
readLine方法只返回回车符之前的数据内容,并不返回回车符。
也就是说读取的内容不会自动换行,可以用newLine方法来换行。
import java.io.*;class CopyTextByBuf { public static void main(String[] args) { BufferedReader bur = null; BufferedWriter buw = null; try { bur = new BufferedReader(new FileReader("RuntimeDemo.java")); buw = new BufferedWriter(new FileWriter("RuntimeDemo_copy.txt")); String line = null; while ((line =bur.readLine())!=null) { buw.write(line); buw.newLine(); buw.flush(); } } catch (IOException e) { throw new RuntimeException("读取写入失败"); } finally { try { if(bur!=null) bur.close(); } catch (IOException e) { throw new RuntimeException("读取关闭失败"); } try { if (buw!=null) buw.close(); } catch (IOException e) { throw new RuntimeException("写入关闭失败"); } } }}
4.流操作的基本规律和方法:
1、
源:键盘录入。
目的:控制台。
2、需求:把键盘录入的数据存储到一个文件中。
源:键盘
目的:文件。
使用字节流通向字符流的转换流:InputStreamReader
3、需求:想要将一个文件的数据打印在控制台上。
源:文件
目的:控制台
使用字符流通向字节流的转换流:OutputStreamWriter
怎样操作流?
1 明确源和目的。
源:输入流。InputStream Reader
目的:输出流。OutputStream Writer
2 操作的数据是否是纯文本。
是:字符流
否:字节流
3 当体系明确后,再明确要使用哪个具体的对象。通过设备来进行区分:
源设备:内存,硬盘,键盘
目的设备:内存,硬盘,控制台
例如:
将一个文本文件中数据存储到另一个文件中。复制文件。
1)源:因为是源,所以使用读取流:InputStream和Reader
明确体系:是否操作文本:是,Reader
明确设备:明确要使用该体系中的哪个对象:硬盘上的一个文件。Reader体系中可以操作文件的对象是FileReader
是否需要提高效率:是,加入Reader体系中缓冲区 BufferedReader.
FileReader fr = new FileReader(“a.txt”);
BufferedReader bufr = new BufferedReader(fr);
2)目的:输出流:OutputStream和Writer
明确体系:是否操作文本:是,Writer
明确设备:明确要使用该体系中的哪个对象:硬盘上的一个文件。Writer体系中可以操作文件的对象FileWriter。
是否需要提高效率:是,加入Writer体系中缓冲区 BufferedWriter
FileWriter fw = new FileWriter(“b.txt”);
BufferedWriter bufw = new BufferedWriter(fw);
5.File类:
File:文件和目录路径名的抽象表现形式
1.用来将文件或者文件夹封装成对象。
2.方便对文件与文件夹的属性信息进行操作。
3.File对象可以作为参数传递给流的构造函数。
演示代码:
import java.io.*;class FileDemo{ public static void main(String[] args) { consMethod(); } public static void consMethod() { //将a.txt封装成file对象,可以将已有的和未出现的文件或者文件夹封装成对象。 File f1 = new File("c:\\abc\\a.txt"); File f2 = new File("c:\\abc","b.txt"); File d = new File("c:\\abc"); File f3 = new File(d,"c.txt"); sop("f1:"+f1); sop("f2:"+f2); sop("f3:"+f3); File f4 = new File("c:"+File.separator+"abc"+File.separator+"zz"+File.separator+"d.txt"); sop("f4:"+f4); } public static void sop(Object obj) { System.out.println(obj); }}
练习:
将一个指定目录下的java文件的绝对路径,存储到一个文本文件中。
建立一个java文件列表文件。
思路:
1.对指定的目录进行递归
2.获取递归过程中所有的java文件的路径。
3.将这些路径存储到集合中。
4.将集合中的数据写入到一个文件中。
import java.io.*;import java.util.*;class JavaFileList{ public static void main(String[] args)throws IOException { File dir = new File("e:\\java2015\\day09"); List<File> list = new ArrayList<File>(); fileToList(dir,list); File file = new File(dir,"javalist.txt"); writeToFile(list,file.toString()); } public static void fileToList(File dir , List<File> list) { File[] files = dir.listFiles(); for (File file : files ) { if (file.isDirectory()) fileToList(file,list); else { if (file.getName().endsWith(".java")) list.add(file); } } } public static void writeToFile(List<File>list,String javalist)throws IOException { BufferedWriter bufw = null; try { bufw = new BufferedWriter(new FileWriter(javalist)); for (File f :list ) { String path = f.getAbsolutePath(); bufw.write(path); bufw.newLine(); bufw.flush(); } } catch (IOException e) { throw e; } finally { try { if(bufw!=null) bufw.close(); } catch (IOException e) { throw e; } } }}
6.Propertieslei :
Properties是Hashtable的子类。
也就是说它具备map集合的特点,而且它里面存储的键值对都是字符串。
是集合和IO技术相结合的集合容器。
该对象的特点,可以用于键值对形式的配置文件。
那么在加载数据时,需要数据有固定格式:键=值。
特有方法
1、设置
Object setProperty(String key,String value);
设置键和值,调用Hashtable的方法put
2、获取
String getProperty(String key);
指定key搜索value
Set stringPropertyName();
返回属性列表的键集,存入Set集合
3、加载流和存入流
void load(InputStream ism);
从输入字节流中读取属性列表(键和元素对)。又称将流中的数据加载进集合。
void load(Readerreader);
从输入字符流中读取属性列表(键和元素对)。又称将流中的数据加载进集合。
voidlist(PrintStream out);//将属性列表输出到指定的输出流
void store(OutputStreamout,String comments);
对应load(InputStream )将属性列表(键值对)写入输出流。comments属性列表的描述。
void store(Writerwriter, String comments);
对应load(Reader)将属性列表(键值对)写入输出流。comments属性列表的描述。
演示代码:
import java.io.*;import java.util.*;class PropertiesDemo{ public static void main(String[] args)throws IOException { //setAndGet(); //method_1(); loadDemo(); } public static void loadDemo() throws IOException { Properties prop = new Properties(); FileInputStream fis = new FileInputStream("info.txt"); //将流中的数据加载进集合。 prop.load(fis); prop.setProperty("wangwu","3113"); FileOutputStream fos = new FileOutputStream("info.txt"); prop.store(fos,"valuechange"); //System.out.println(prop); prop.list(System.out); fos.close(); fis.close(); } //想要将info.txt中键值数据存到集合中操作。 /* 1.用一个流和info.txt文件关联。 2.读取一行数据,将该行数据用"="进行切割。 3.等号左边作为键,右边作为值,存入到properties集合中即可。 */ public static void method_1()throws IOException { BufferedReader bufr = new BufferedReader(new FileReader("info.txt")); String line = null ; Properties prop = new Properties(); while ((line=bufr.readLine())!=null) { String[] arr = line.split("="); //System.out.println(arr[0]+"..."+arr[1]); prop.setProperty(arr[0],arr[1]); } bufr.close(); System.out.println(prop); } public static void setAndGet() { Properties prop = new Properties(); prop.setProperty("zhangsan","3"); prop.setProperty("zhangsan",23+""); prop.setProperty("lisi","6"); prop.setProperty("wangsan","9"); Set<String> names = prop.stringPropertyNames(); for (String s : names ) { System.out.println(s+":"+prop.getProperty(s)); } }}
小练习:
需求:
有五个学生,每个学生有3门课的成绩,
从键盘上输入以上数据(包括姓名,三门课成绩)
输入的格式:如 zhangsan,20,30,50 计算出总成绩。
并把学生的信息和计算出的总分数高低顺序存放在磁盘文件”stud.txt”中。
1.描述学生对象
2.定义一个可操作学生对象的工具类。
思路:
1.通过获取键盘录入一行数据,并将该行数据的信息取出封装成学生对象。
2.因为学生对象有很多,需要集合存储,要对学生的总分排序。要用到TreeSet。
3.将集合中的信息写入到一个文件中。
import java.util.*;import java.io.*;class Student implements Comparable<Student>{ private String name; private int ma,cn,en; private int sum; Student(String name ,int ma,int cn,int en) { this.name = name; this.ma = ma; this.cn = cn; this.en = en; sum = ma + cn + en; } public int compareTo(Student s) { int num = new Integer(this.sum).compareTo(new Integer(s.sum)); if(num==0) return this.name.compareTo(s.name); return num; } public String getName() { return name; } public int getSum() { return sum; } public int hasCode() { return name.hashCode()+sum*18; } public boolean equals(Object obj) { if(!(obj instanceof Student)) throw new ClassCastException("类型不匹配"); Student s = (Student)obj; return this.name.equals(s.name) && this.sum == s.sum; } public String toString() { return "student["+name+","+ma+","+cn+","+en+"]"; }}class StudentInfoTool{ public static Set<Student>getStudents()throws IOException { return getStudents(null); } public static Set<Student>getStudents(Comparator<Student> cmp)throws IOException { BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in)); String line = null; Set<Student> stus = null; if(cmp==null) stus=new TreeSet<Student>(); else stus=new TreeSet<Student>(cmp); while ((line = bufr.readLine())!=null) { if("over".equals(line)) break; String[] info = line.split(","); Student stu = new Student(info[0],Integer.parseInt(info[1]), Integer.parseInt(info[2]), Integer.parseInt(info[3])); stus.add(stu); } bufr.close(); return stus; } public static void writeToFile(Set<Student> stus)throws IOException { BufferedWriter bufw = new BufferedWriter(new FileWriter("stud.txt")); for(Student stu :stus) { bufw.write(stu.toString()+"\t"); bufw.write(stu.getSum()+""); bufw.newLine(); bufw.flush(); } bufw.close(); }}class StudentInfoTest { public static void main(String[] args) throws IOException { Comparator<Student> cmp =Collections.reverseOrder(); Set<Student> stus = StudentInfoTool.getStudents(cmp); StudentInfoTool.writeToFile(stus); }}
——Java培训、Android培训、iOS培训、.Net培训、期待与您交流! ——-
- 黑马程序员—io流
- 黑马程序员—IO流
- 黑马程序员—IO流
- 黑马程序员 — IO流
- 黑马程序员—IO流
- 黑马程序员—IO流
- 黑马程序员—IO流
- 黑马程序员—IO流
- 黑马程序员—IO流
- 黑马程序员 IO流
- 黑马程序员IO流
- 黑马程序员-IO流
- 黑马程序员---IO流
- 黑马程序员-----IO流
- 黑马程序员--io流
- 黑马程序员:IO流
- 黑马程序员----IO流
- 黑马程序员--IO流
- ListView 滑动时数据重复错位解决
- Android第三讲——五大布局(UI)
- 《UNIX环境高级编程》笔记--线程的取消选项
- 题目:二叉树的后序遍历
- 滚动CollectionView控制PageControl实现分页浏览的效果
- 黑马程序员—IO流
- 在delphi中Char,PChar,PByte,Byte,String的相互转换示例
- 题目:二叉树的最大深度
- 析构函数抛出异常
- Delphi流操作技巧
- HDU-1875 畅通工程再续(最小生成树[Prim])
- 题目:二叉树的最小深度
- 初步篇7分支结构程序体验项目1求两数正差值
- PHP foreach 的用法