黑马程序员--字节流,转换流(重要,很简单,就那么几个格式)

来源:互联网 发布:hashset源码解析 编辑:程序博客网 时间:2024/05/19 19:40

----------------------ASP.Net+Android+IOS开发.Net培训、期待与您交流! ----------------------

字节流:
InputStream
OutputStream

FileOutputStream在输出时是不用刷新的。

介绍一下字节读写流的基本用法。

import java.io.*;class StreamDemo1{public static void main(String[] args){//outFile();//inFile();inFile_2();}public static void inFile()//这是通用的读取方法。{FileInputStream fis = null;try{fis = new FileInputStream("f:\\io\\1.txt");byte[] ch = new byte[1024];int num = 0;while((num=fis.read(ch))!=-1){System.out.print(new String(ch,0,num));}}catch (IOException ex){System.out.println(ex.toString());}finally{if (fis!=null){try{fis.close();}catch (IOException ex){System.out.println(ex.toString());}}}}public static void inFile_2()//这一种方法只能操作数据很少的文件。{FileInputStream fis = null;try{fis = new FileInputStream("f:\\io\\1.txt");int num = 0;num = fis.available();//这个方法返回的是数据的大小byte[] ch = new byte[num];fis.read(ch);System.out.print(new String(ch));}catch (IOException ex){System.out.println(ex.toString());}finally{if (fis!=null){try{fis.close();}catch (IOException ex){System.out.println(ex.toString());}}}}public static void outFile(){FileOutputStream fos = null;try{fos = new FileOutputStream("f:\\io\\2.txt");fos.write("abcdefg".getBytes());}catch (IOException ex){System.out.println(ex.toString());}finally{if (fos!=null){try{fos.close();}catch (IOException ex){System.out.println(ex.toString());}}}}}

练习:复制一个mp3。

import java.io.*;class StreamDemo2 {public static void main(String[] args) {long l1 = System.currentTimeMillis();copyFile();long l2 = System.currentTimeMillis();System.out.println(l2-l1);}public static void copyFile(){FileOutputStream fos = null;FileInputStream fis = null;try{fos = new FileOutputStream("f:\\io\\1(2).avi");fis = new FileInputStream("f:\\io\\1.avi");byte[] ch = new byte[1024];int num = 0;while ((num=fis.read(ch))!=-1){fos.write(ch,0,num);}}catch (IOException ex){System.out.println(ex.toString());}finally{if (fis!=null){try{fis.close();}catch (IOException ex){System.out.println(ex.toString());}}if (fos!=null){try{fos.close();}catch (IOException ex){System.out.println(ex.toString());}}}}}
练习:复制一个mp3。

利用Buffer提高效率。

为什么读一个byte返回的却是一个int?
因为返回的二进制值有可能全部是1,换成byte就是-1了。
所以,在返回的值前面加上0,变成int,它就不可能是-1了。
如何加0呢?用byte&255就可以了。。
写一个数据的时候,传入的是int,但写入的其实是一个byte。前面的24个0会去掉的哟


import java.io.*;class StreamDemo3{public static void main(String[] args) {long l1 = System.currentTimeMillis();copyFile();long l2 = System.currentTimeMillis();System.out.println(l2-l1);}public static void copyFile(){BufferedOutputStream bos = null;BufferedInputStream bis = null;try{bos = new BufferedOutputStream(new FileOutputStream("f:\\io\\1(1).avi"));bis = new BufferedInputStream(new FileInputStream("f:\\io\\1.avi"));byte[] ch = new byte[1024];int num = 0;while ((num=bis.read(ch))!=-1)//为什么这里返回的是int不是byte。{bos.write(ch,0,num);}}catch (IOException ex){System.out.println(ex.toString());}finally{if (bis!=null){try{bis.close();}catch (IOException ex){System.out.println(ex.toString());}}if (bos!=null){try{bos.close();}catch (IOException ex){System.out.println(ex.toString());}}}}}
System.in
InputStreamReader转换流。

in这个常量它的类型是InputStream。
转换流常和System.in一起用。要记住了哟。

练习:
读取键盘,当回车时就返回一行数据。
如果输入的是over就结束程序。

import java.io.*;class StreamDemo4 {public static void main(String[] args) {systemIn();}public static void systemIn(){BufferedReader br = null;try{br = new BufferedReader(new InputStreamReader(System.in));String line = null;while(!(line=br.readLine()).equals("over"))//注意了,这里是equals。比较两个字符串要用equals而不是=={System.out.println(line);}}catch (IOException ex){System.out.println(ex.toString());}finally{if (br!=null){try{br.close();}catch (IOException ex){System.out.println(ex.toString());}}}}}

转换流:
OutputStreamWriter

把字符流转换成字节流输出。
键盘输入和控制台输出,使用的都是字节数据。不好操作。转换成字符更容易操作。
还有一点。把键盘输入存入文件,用转换流可以指定编码表。默认是GBK

就在这里面写吧。System中的两个方法。改变标准输入输出设备。
System.setIn(new FileInputStream(2.txt));
System.setOut(new PrintStream(3.txt));
不常用。知道就好了。

import java.io.*;class StreamDemo5 {public static void main(String[] args) {systemIn();}public static void systemIn(){BufferedReader br = null;BufferedWriter bw = null;try{br = new BufferedReader(new InputStreamReader(System.in));bw = new BufferedWriter(new OutputStreamWriter(System.out));String line = null;while(!(line=br.readLine()).equals("over"))//注意了,这里是equals。比较两个字符串要用equals而不是=={bw.write(line.toCharArray());bw.newLine();bw.flush();//System.out.write(line.getBytes());//这是直接把数据转成字节流输出。但是想在数据后面加一个回车。哎。}}catch (IOException ex){System.out.println(ex.toString());}finally{if (br!=null){try{br.close();}catch (IOException ex){System.out.println(ex.toString());}}if (bw!=null){try{bw.close();}catch (IOException ex){System.out.println(ex.toString());}}}}}
记录系统异常日志信息。
Throwable.printStackTrace(printStream);

有一个jar包专门实现这个功能
log4j

import java.io.*;import java.util.*;import java.text.*;class StreamDemo6 {public static void main(String[] args) throws Exception{try{int[] ch = new int[1];ch[1] = 5;}catch (Exception ex){Date d = new Date();SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");PrintStream ps = new PrintStream("f:\\io\\1.log");ps.println(sdf.format(d));ex.printStackTrace(ps);}}}

打印系统信息到文件中。
getProperties 
lise(printStream)

import java.io.*;class  StreamDemo7{public static void main(String[] args) throws IOException{System.getProperties().list(new PrintStream("f:\\io\\1.txt"));}}
有五个学生,每个学生有3门课的成绩,
从键盘输入以上数据(包括姓名,三门课成绩),
输入的格式:如:zhagnsan,30,40,60计算出总成绩,
并把学生的信息和计算出的总分数高低顺序存放在磁盘文件"stud.txt"中。


1,描述学生对象。
2,定义一个可操作学生对象的工具类。

import java.io.*;import java.util.*;class StreamTest {public static void main(String[] args)throws IOException {StudentTools stl = new StudentTools();stl.writeStudent();stl.printStudent();}}class Student implements Comparable<Student>//学生类。{public String name;private int math;private int chinese;private int english;public int he;Student(String name,int chinese,int math,int english){this.name = name;this.chinese = chinese;this.math = math;this.english = english;he = chinese+math+english;}public int compareTo(Student stu)//自带的比较器{int num = new Integer(this.he).compareTo(new Integer(stu.he));if (num==0){return this.name.compareTo(stu.name);}return num;}public String toString()//写出去时数据的样式。{return name+"\t"+"语文:"+chinese+"  数学:"+math+"  英语:"+english+"  总分"+he;}}class myComparator implements Comparator<Student>//自定义的学生比较器。{public int compare(Student s1,Student s2){int num = new Integer(s1.he).compareTo(new Integer(s2.he));if (num==0){return s1.name.compareTo(s2.name);}return num;}}class StudentTools//操作学生的工具类{private File file;StudentTools(){file = new File("f:\\io\\Student.txt");}public void writeStudent()throws IOException//把学生数据写出到硬盘。{file.createNewFile();BufferedWriter bw = new BufferedWriter(new FileWriter(file,file.exists()));BufferedReader bis = new BufferedReader(new InputStreamReader(System.in));TreeSet<Student> ts = new TreeSet<Student>(Collections.reverseOrder(new myComparator()));System.out.println("----------输入over结束----------");System.out.println("------输入成绩是用逗号隔开------");while (true){System.out.print("请输入姓名:");String name = bis.readLine();if ("over".equals(name)){break;}System.out.print("请输入成绩:");String  result = bis.readLine();if ("over".equals(result)){break;}//把输入的成绩转成intString[] ress = result.split(",");int[] resi = new int[3];try{for (int x=0; x<ress.length&&x<resi.length; x++){resi[x] = Integer.parseInt(ress[x]);}}catch (Exception ex){System.out.println("------输入错误------");System.out.println("------重新输入------");continue;}//把键盘数据转成对象,存入集合。Student stu = new Student(name,resi[0],resi[1],resi[2]);ts.add(stu);}//从集合中取出数据,存入硬盘。Iterator<Student> it = ts.iterator();while (it.hasNext()){Student s = it.next();bw.write(s.toString());bw.newLine();}//关闭资源。bis.close();bw.close();}public void printStudent()throws IOException//把学生数据打印出来。{System.out.println("------学生成绩目录------");BufferedReader br = new BufferedReader(new FileReader(file));String str = null;while ((str=br.readLine())!=null){System.out.println(str);}br.close();System.out.println("文件保存在:"+file);}}


----------------------ASP.Net+Android+IOS开发.Net培训、期待与您交流! ----------------------

0 0
原创粉丝点击