关于IO流的总结

来源:互联网 发布:php配置环境工具 编辑:程序博客网 时间:2024/05/20 00:49


1、IO流的概述

(1)用于处理设备之间的数据传输

(2)Java对数据的操作是通过流的方式

(3)Java用于操作流的对象都在IO包中

(4)流按操作数据分为两种:字节流和字符流

(5)流按流向分为两种:输入流和输出流

2、字符流

(1)抽象基类:ReaderWriter.

(2)文本写入数据

代码示例:

package io;import java.io.*;public class FileWriterDemo1 {public static void main(String [] args)throws IOException{//创建一个fileWriter对象,该对象一被初始化,就必须要明确被操作的文件,而且该文件会被创建到指定目录下,//如果该目录下已有同名文件,将被覆盖。FileWriter fw=new FileWriter("file\\demo.txt");//调用writer方法,将字符串写入到流中fw.write("dafofn");//刷新流对象中的缓冲中数据,将数据刷到目的地中fw.flush();fw.close();}}


package io;import java.io.*;public class FileWriterDemo2 {/** * @param args */public static void main(String[] args) {FileWriter fw=null;try{fw=new FileWriter("file\\demo2.txt");fw.write("abddd");}catch(IOException e){System.out.println(e.toString());}finally{try{if(fw!=null)fw.close();}catch(IOException e){e.toString();}}}}



(3)文本续写数据

代码示例:

package io;import java.io.*;public class FileWriterDemo3 {/** * @param args */public static void main(String[] args) throws IOException{//传递一个true参数,代表不覆盖已有的文件,并且在已有文件的末尾处进行数据续写FileWriter fw=new FileWriter("file\\Demo.txt",true);fw.write("nihao\r\nxiexie");fw.close();}}


(4)文本读取方式一

代码示例:

package io;import java.io.*;public class FileReaderDemo1 {public static void main(String [] args)throws IOException{//创建一个文件读取流对象,和指定名称的文件相关联,要保证流文件是已经存在的,如果不存在//会发生异常FileNotFoundExceptionFileReader fr=new FileReader("file\\demo.txt");//调用读取流对象的read方法int ch=0;while((ch=fr.read())!=-1){System.out.print((char)ch);}}}


(5)文本读取方式二

代码示例:

package io;import java.io.*;public class FileReaderDemo2 {/** * @param args */public static void main(String[] args) throws IOException{FileReader fr=new FileReader("file\\demo2.txt");//定义一个字符数组,用于存储独到字符,该read(char[])返回的是读到字符个数char[] buf=new char[1024];int num=0;while((num=fr.read(buf))!=-1){System.out.print(new String(buf,0,num));}fr.close();}}


(6)复制文本文件

i. 思想

1. 在指定目录创建一个文件,用于存储数据

2. 定义一个读取流和源文件关联

3. 通过不断的读写完成数据存储

4. 关闭资源

ii. 代码实现

package io;import java.io.*;public class Copy {/** * @param args */public static void main(String[] args)throws IOException{copy_2();}public static void copy_1()throws IOException{//创建目的地FileWriter fw=new FileWriter("file\\copy1.txt");//与已知文件关联FileReader fr=new FileReader("file\\FileReaderDemo1.java");int ch=0;while((ch=fr.read())!=-1)fw.write(ch);fw.close();fr.close();}public static void copy_2()throws IOException{FileWriter fw=null;FileReader fr=null;try{fw=new FileWriter("copy2.txt");fr=new FileReader("FileReaderDemo1.java");char[] buf=new char[1024];int len=0;while((len=fr.read(buf))!=-1){fw.write(buf, 0, len);}}catch(IOException e){throw new RuntimeException("读写失败!");}finally{if(fr!=null){try{fr.close();}catch(IOException e){throw new RuntimeException("fr关闭失败!");}}if(fw!=null){try{fw.close();}catch(IOException e){throw new RuntimeException("fw关闭失败!");}}}}}


(7)字符流写入缓冲区

代码示例:

package io;import java.io.*;public class BufferedWriterDemo {/** * 缓冲区的的出现是为了提高流的操作效率,所以在创建缓冲区之前,必须要先有流对象 */public static void main(String[] args)throws IOException{bufferedWriter();}public static void bufferedWriter() throws IOException{//创建流对象,关联写入文件FileWriter fw=new FileWriter("file\\buffreredWriter.txt");//创建缓冲区BufferedWriter bufw=new BufferedWriter(fw);//写入数据for(int x=1;x<5;x++){bufw.write("abce"+x);bufw.newLine();bufw.flush();}//关闭缓冲区bufw.close();}}


(8)字符流读取缓冲区

代码示例:

package io;import java.io.*;public class BufferedReaderDemo {/** * @param args */public static void main(String[] args) throws IOException{//创建一个读取流对象和文件相关联FileReader fr=new FileReader("file\\FileReaderDemo1.java");//创建写入缓冲区BufferedReader bufr=new BufferedReader(fr);String line=null;//读取数据while((line=bufr.readLine())!=null){System.out.println(line);}//关闭缓冲区bufr.close();}}


(9)通过缓冲区复制文件

代码示例:

package io;import java.io.*;public class CopyByBuf {/** * @param args */public static void main(String[] args) {//创建读写缓冲区BufferedReader bufr=null;BufferedWriter bufw=null;try{//关联读取文件bufr=new BufferedReader(new FileReader("file\\FileReaderDemo1.java"));//关联写入文件bufw=new BufferedWriter(new FileWriter("file\\copyByBuf.txt"));String line=null;//写入文件while((line=bufr.readLine())!=null){bufw.write(line);bufw.newLine();bufw.flush();}}catch(IOException e){throw new RuntimeException("失败!");}//关闭资源finally{try{bufr.close();}catch(IOException e){throw new RuntimeException("失败!");}try{bufw.close();}catch(IOException e){throw new RuntimeException("失败!");}}}}


(10)readLine的方法

i. 原理:

无论读一行还是读取多个字符,其实最终都是在硬盘上一个一个读取,所以最终使用的还是read()方法。

ii. 代码示例:

package io;import java.io.*;public class MyBufferedReader {//定义读取文件对象private FileReader r;//重定义构造函数,传入对象public 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();elsesb.append((char)ch);}if(sb.length()!=0)return sb.toString();return null;}//自定义关闭资源public void myClose()throws IOException{r.close();}}


3、字节流

(1)抽象基类:InputStreamOutputStream

(2)文本读取方式一

代码示例:

//通过定义合适的字节数组来一次读取文件public static void readFile_1()throws IOException{FileInputStream fis=new FileInputStream("file\\FileReaderDemo1.java");byte[] buf=new byte[fis.available()];fis.read(buf);sop(new String(buf));fis.close();}


(3)文本读取方式二

代码示例:

//通过定义一定大小的字节数组来读取文件public static void readFile_2()throws IOException{FileInputStream fis=new FileInputStream("file\\FileReaderDemo1.java");byte[] buf=new byte[1024];int len=0;while((len=fis.read(buf))!=-1){sop(new String(buf,0,len));}}


(4)文本读取方式三

代码示例:

//一个字节一个字节的读取文件public static void readFile_3()throws IOException{FileInputStream fis=new FileInputStream("file\\FileREaderDemo1.java");int ch=0;while((ch=fis.read())!=-1){sop((char)ch);}fis.close();}


(5)文本写入方式

代码示例:

public static void writeFile()throws IOException{FileOutputStream fos=new FileOutputStream("file\\Stream.txt");fos.write("fbsifbisbfiue".getBytes());fos.close();}


(6)复制图片

i. 思路

1. 用字节流读取流对象和图片对象关联

2. 用字节写入流对象创建一个图片文件,用于存储获取到的图片数据

3. 通过循环读写,完成数据的存储

4. 关闭资源

ii. 代码实现:

package io;import java.io.*;public class CopyPic {/** * @param args */public static void main(String[] args) {FileOutputStream fos=null;FileInputStream fis=null;try{//用字节流读取流对象和图片对象关联fis=new FileInputStream("file\\question.gif");//用字节写入流对象创建一个图片文件,用于存储获取到的图片数据fos=new FileOutputStream("picture\\question.gif");byte[] buf=new byte[1024];int len=0;//3.通过循环读写,完成数据的存储while((len=fis.read(buf))!=-1){fos.write(buf,0,len);}}catch(IOException e){}//关闭资源finally{try{if(fos!=null)fos.close();}catch(IOException e){}try{if(fis!=null)fis.close();}catch(IOException e){}}}}


(7)复制MP3

代码示例:

public static void copy()throws IOException{BufferedInputStream bufis=new BufferedInputStream(new FileInputStream("file\\周杰伦 - 彩虹天堂.mp3"));BufferedOutputStream bufos=new BufferedOutputStream(new FileOutputStream("music\\周杰伦 - 彩虹天堂.mp3"));int by=0;while((by=bufis.read())!=-1)bufos.write(by);bufos.close();bufis.close();}


(8)自定义缓冲区

代码示例:

package io;import java.io.*;public class MyBufferedInputStream {private InputStream in;private byte[] buf=new byte[1024*4];private int pos=0,count=0;public MyBufferedInputStream(InputStream in) {this.in=in;}//一次读一个字节,从缓冲区获取public int myRead()throws IOException{if(count==0){//通过in对象读取键盘上数据并存储buf中count=in.read(buf);if(count<0)return -1;pos=0;byte b=buf[pos];count--;pos++;return b&255;}else if(count>0){byte b=buf[pos];count--;pos++;return b&255;}return -1;}//自定义关闭资源public void myClose()throws IOException{in.close();}}


4、读取键盘录入

(1)System.out:对应的是标准输出设备控制台

(2)System.in:对应的是标准输入设备键盘

(3)实例:键盘录入数据,以over结束

代码示例:

package io;import java.io.*;public class ReadIn {/** * @param args */public static void main(String[] args) throws IOException{//定义标准输入对象InputStream in=System.in;//定义字符串缓冲区StringBuilder sb=new StringBuilder();while(true){//读取数据int ch=in.read();if(ch=='\r')continue;if(ch=='\n'){String s=sb.toString();if("over".equals(s))break;//以over结束输入System.out.print(s.toUpperCase());//输出大写字母sb.delete(0,sb.length());//清空缓冲区}elsesb.append((char)ch);//添加字符}}}


5、字符流与字节流的转换

(1)字节流转换成字符流:

代码示例:

package io;import java.io.*;public class TransStreamDemo {/** * @param args */public static void main(String[] args)throws IOException{//获取键盘录入对象InputStream in=System.in;//将字节流转换成字符流对象,使用字符转换流InputStreamReader isr=new InputStreamReader(in);//为了提高效率,将字符串进行缓冲区技术高效操作BufferedReader bufr=new BufferedReader(isr);String line=null;while((line=bufr.readLine())!=null){if("over".equals(line))break;System.out.println(line.toUpperCase());}bufr.close();}}


(2)字符流转换成字节了:

代码示例:

package io;import java.io.*;public class TransStreamDemo2 {/** * @param args *///字符流转字节流public static void main(String[] args) throws IOException{BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in ));BufferedWriter bufw=new BufferedWriter(new OutputStreamWriter(System.out));String line=null;while((line=bufr.readLine())!=null){if("over".equals(line))break;bufw.write(line.toUpperCase());bufw.newLine();bufw.flush();}bufr.close();}}


6、流的操作规律

通过三个明确来完成

(1)明确源和目的

i. 源:输入流:InputStream  Reader

ii. 目的:输出流:OutputStream Writer

(2)明确操作的数据是否是纯文本

i. 是:字符流

ii. 否:字节流

(3)明确要使用哪个具体对象,通过设备来进行区分

i. 源设备:

1. 内存:System.in

2. 硬盘:FileStream

3. 键盘:ArrayStream

ii. 目的设备:

1. 内存:System.out

2. 硬盘:FileStream

3. 控制台:ArrayStream

 

7、异常日志文件

代码示例:

package io;import java.io.*;import java.text.*;import java.util.Date;public class ExceptionInfomation {/** * @param args */public static void main(String[] args) {try{int[] arr=new int[2];System.out.println(arr[3]);}catch(Exception e){try{//获取异常时间Date d=new Date();SimpleDateFormat sdf=new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");String s=sdf.format(d);//将异常信息存入Exception.log中PrintStream ps=new PrintStream("file\\Exception.log");ps.println(s);System.setOut(ps);}catch(IOException ex){throw new RuntimeException("失败!");}e.printStackTrace(System.out);}}}


8、File

(1)常见方法

i. 创建

Boolean createNewFile()

//在指定位置创建文件,如果该文件已经存在,则不创建,返回false。和输出  //流不一样,输出流对象建立创建文件时,文件存在会被覆盖。

Boolean mkdir()

//创建文件夹

Boolean mkdirs()

//创建多级目录

ii. 删除

Boolean delete();

//删除失败返回假

Void deleteOnExit();

//在程序推出时删除指定文件

iii. 判断

Boolean exits()

ifFile()

isDirectory()

isHidden()

isAbsolute()

iv. 获取

getName();

getPath()

getParent()

//该方法返回的是觉得路径的父目录

getAbsolute()

lastModified()

length();

v. 重命名

renameTo()

vi. 列出

ListRoots()

List()

(2)获取多级目录

代码示例:

//获取多级目录public static void showDir(File dir){sop(dir);File[] files=dir.listFiles();for(int x=0;x<files.length;x++){if(files[x].isDirectory())showDir(files[x]);elsesop(files[x]);}}


(3)加过滤器获取指定后缀名的文件

代码示例:

public static void fileNameFilter(){File dir=new File("E:\\MyEclipse\\demo\\file");String[] arr=dir.list(new FilenameFilter(){public boolean accept(File dir,String name){return name.endsWith(".mp3");}});System.out.println("len="+arr.length);for(String name:arr){System.out.println(name);}}


(4)实例:将指定的文件的绝对路径存到文本文件中

i. 思路:

1. 对指定的目录进行递归

2. 获取递归过程中所有的java文件的路径

3. 将这些路径存储到集合中

4. 将集合中的数据写入到一个文件中

ii. 代码实现

 

package io;import java.io.*;import java.util.ArrayList;import java.util.List;public class JavaFileList {/** * @param args */public static void main(String[] args)throws IOException{File dir=new File("E:\\MyEclipse\\demo");List<File> list=new ArrayList<File>();fileToList(dir,list);File file=new File(dir,"file\\javaList.txt");writeToFile(list,file.toString());}//获取递归过程所有的java文件的路径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 javaListFile)throws IOException{BufferedWriter bufw=null;try{bufw=new BufferedWriter(new FileWriter(javaListFile));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;}}}}

9、Properties

(1)概述

Propertieshashtable的子类,即它具备map集合的特点,而且它里面存储的键值对都是字符串,是集合和IO技术相结合的集合容器。对象的特点:可以用于以键值对的形式的配置文件,加载数据时,需要数据固定格式:键=值。

(2)设置和获取元素

代码示例:

public static void setAndGet(){Properties prop=new Properties();prop.setProperty("zhangsan", "30");prop.setProperty("lisi", "39");String value=prop.getProperty("lisi");prop.setProperty("lisi", "66");Set<String> names=prop.stringPropertyNames();for(String s:names){System.out.println(s+":"+prop.getProperty(s));}}


(3)将info.txt中的键值数据存储到集合中

i. 思路:

1. 用一个流和info.txt文件关联

2. 读取一行数据,将该行数据用“=“进行切割

3. 等号左边作为键,右边作为值存入到properties集合中。

ii. 代码实现

public static void method()throws IOException{BufferedReader bufr=new BufferedReader(new FileReader("file\\info.txt"));String line=null;Properties pro=new Properties();while((line=bufr.readLine())!=null){String[] arr=line.split("=");pro.setProperty(arr[0], arr[1]);}bufr.close();System.out.print(pro);}



(4)记录应用程序运行次数

i. 思路:

使用计数器,程序即使结束,该计数器的值也存在,下次程序启动会再加载该计数器的值并加1后重新存储到计数器,所以要建立一个配置文件,用于记录该软件的启动次数,该配置文件使用键值对的方式,这样便于阅读数据并操作数据。

ii. 代码实现

 

package io;import java.io.*;import java.util.*;public class RunCount {/** * @param args */public static void main(String[] args)throws IOException{Properties prop=new Properties();File file=new File("file\\count.ini");if(!file.exists())file.createNewFile();FileInputStream fis=new FileInputStream(file);prop.load(fis);int count=0;String value=prop.getProperty("time");if(value!=null){count=Integer.parseInt(value);if(count>=5){System.out.print("过期");return ;}}count++;prop.setProperty("time", count+"");FileOutputStream fos=new FileOutputStream(file);prop.store(fos, "");fos.close();fis.close();}}

10、打印流

a) 字节打印流PrintStream构造函数可以接收的参数类型

i. File对象:File

ii. 字符串路径:String

iii. 字节输出流:OutputStream

b) 字符打印流PrintWrite构造函数可以接收的参数类型

i. File对象:File

ii. 字符串路径:String

iii. 字节输出流:OutputStream

iv. 字符输出流:Writer

c) 代码实例

package io;import java.io.*;public class PritStreamDemo {/** * @param args */public static void main(String[] args) throws IOException{BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));PrintWriter out=new PrintWriter(new FileWriter("file\\print.txt"));String line=null;while((line=bufr.readLine())!=null){if("over".equals(line))break;out.println(line.toUpperCase());}out.close();bufr.close();}}


11、序列流

a) 三个文件内容输入到第四个文件中

代码示例:

package io;import java.io.*;import java.util.*;public class SequenceDemo {/** * @param args */public static void main(String[] args)throws IOException{Vector<FileInputStream> v=new Vector<FileInputStream>();v.add(new FileInputStream("file\\1.txt"));v.add(new FileInputStream("file\\2.txt"));v.add(new FileInputStream("file\\3.txt"));Enumeration<FileInputStream> en=v.elements();SequenceInputStream sis=new SequenceInputStream(en);FileOutputStream fos=new FileOutputStream("file\\4.txt");byte[] buf=new byte[1024];int len=0;while((len=sis.read(buf))!=-1){fos.write(buf,0,len);}fos.close();sis.close();}}


b) 文件切割与合并

代码示例:

package io;import java.io.*;import java.util.ArrayList;import java.util.Enumeration;import java.util.Iterator;public class FileSplitMerge {/** * @param args */public static void main(String[] args) throws IOException{//splitFile();merge();}//将文件切割public static void splitFile()throws IOException{FileInputStream fis=new FileInputStream("file\\周杰伦 - 彩虹天堂.mp3");FileOutputStream fos=null;byte[] buf=new byte[1024*1024];int len=0;int count=1;while((len=fis.read(buf))!=-1){fos=new FileOutputStream("music\\"+(count++)+".part");fos.write(buf,0,len);fos.close();}fis.close();}//将切割的碎片文件合并public static void merge()throws IOException{ArrayList<FileInputStream> al=new ArrayList<FileInputStream>();for(int x=1;x<=12;x++){al.add(new FileInputStream("music\\"+x+".part"));}final Iterator <FileInputStream> it=al.iterator();Enumeration <FileInputStream> en=new Enumeration<FileInputStream>(){public boolean hasMoreElements(){return it.hasNext();}public FileInputStream nextElement(){return it.next();}};SequenceInputStream sis=new SequenceInputStream(en);FileOutputStream fos=new FileOutputStream("music\\彩虹天堂.mp3");byte[] buf=new byte[1024];int len=0;while((len=sis.read(buf))!=-1){fos.write(buf,0,len);}fos.close();sis.close();}}


c) 对象序列化

代码示例:

package io;import java.io.*;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;public class ObjectStreamDemo {/** * @param args */public static void main(String[] args) throws Exception{//writeObj();readObj();}//读取对象public static void readObj()throws Exception{ObjectInputStream ois=new ObjectInputStream(new FileInputStream("file\\obj.txt"));Person p=(Person)ois.readObject();System.out.println(p);ois.close();}//写入对象public static void writeObj()throws Exception{ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("file\\obj.txt"));oos.writeObject(new Person("lisi",33,"cn"));oos.close();}}//定义一个人的类class Person implements Serializable{public static final long serialVesionUID=42L;private String name;transient int age;static String country="cn";Person(String name,int age,String country){this.name=name;this.age=age;this.country=country;}public String toString(){return name+":"+age+":"+country;}}


12、管道流

代码示例:

package io;import java.io.*;public class PipeStreamDemo {/** * @param args * @throws InterruptedException  */public static void main(String[] args) throws IOException, InterruptedException{PipedInputStream in=new PipedInputStream();PipedOutputStream out=new PipedOutputStream();in.connect(out);Read r=new Read(in);Write w=new Write(out);Thread t=new Thread(r);t.start();t.sleep(3000);new Thread(w).start();}}//管道读取流class Read implements Runnable{private PipedInputStream in;Read(PipedInputStream in){this.in=in;}public void run(){try{byte[] buf=new byte[1024];int len=in.read(buf);String s=new String(buf,0,len);System.out.println(s);in.close();}catch(IOException e){throw new RuntimeException("读取文件失败!");}}}//管道写入流class Write implements Runnable{private PipedOutputStream out;Write(PipedOutputStream out){this.out =out;}public void run(){try{out.write("pipe is comming".getBytes());out.close();}catch(IOException e){throw new RuntimeException("输入失败!");}}}


13、RandomAccessFile

a) 概述

该类不是IO体系中的子类,而是直接继承Object,但是它是IO包中成员,因为它具备读写功能,内部封装了封装一个数组,而且通过指针对数组的元素进行操作,可以通过getFilePointer获取指针位置,同时可以通过seek改变指针的位置,其实完成读写的原理,就是内部封装了字节输入流和输出流。通过构造函数可以看出,该类只能操作文件,而且操作文件还有模式:r,rw

b) 代码示例

<span style="white-space:pre"></span>//写入文件public static void writeFile()throws IOException{RandomAccessFile raf=new RandomAccessFile("file\\random.txt","rw");raf.write("李四".getBytes());raf.writeInt(98);raf.write("wangwu".getBytes());raf.writeInt(88);raf.close();}<span style="white-space:pre"></span>//读取文件public static void readFile()throws IOException{RandomAccessFile raf=new RandomAccessFile("file\\random.txt","r");//调整对象中指针raf.seek(8);//跳过指定的字节数//raf.skipBytes(8);byte[] buf=new byte[4];raf.read(buf);String name=new String(buf);int age=raf.readInt();System.out.println("name="+name);System.out.println("age="+age);raf.close();}


14、DataStream

a) DataInputStreamDataOutputStrem用于操作基本数据类型的数据流对象

b) 代码示例

package io;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;public class DataDemo {/** * @param args */public static void main(String[] args)throws IOException {/*writeUTFDemo();readUTFDemo();*/writeData();readData();}public static void readUTFDemo()throws IOException{DataInputStream dis=new DataInputStream(new FileInputStream("file\\uftdata.txt"));String s=dis.readUTF();System.out.println(s);dis.close();}public static void writeUTFDemo()throws IOException{DataOutputStream dos=new DataOutputStream(new FileOutputStream("file\\uftdata.txt"));dos.writeUTF("您好");dos.close();}public static void readData()throws IOException{DataInputStream dis=new DataInputStream(new FileInputStream("file\\data.txt"));int num=dis.readInt();boolean b=dis.readBoolean();double d=dis.readDouble();sop(num);sop(b);sop(d);dis.close();}public static void writeData()throws IOException{DataOutputStream dos=new DataOutputStream(new FileOutputStream("file\\data.txt"));dos.writeInt(234);dos.writeBoolean(true);dos.writeDouble(89797.323);dos.close();}public static void sop(Object obj){System.out.println(obj);}}


15、ByteArrayStream

a) ByteArrayInputStreamByteArrayOutputSteam操作字节数组

b) ByteArrayInputStream:在构造的时候需要接收数据源,而且数据源是一个字节数组

c) ByteArrayOutputStream:在构造的时候不用定义数据目的,因为该对象中内部已经封装了可变长度的字节数组,这就是数组目的地。

d) 代码示例:

package io;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;public class ByteArrayStream {/** * @param args */public static void main(String[] args) {ByteArrayInputStream bis=new ByteArrayInputStream("ABCD".getBytes());ByteArrayOutputStream bos=new ByteArrayOutputStream();int by=0;while((by=bis.read())!=-1){bos.write(by);}System.out.println(bos);}}


16、字符编码

a) Iso8859-1GBK UTF-8

b) 代码示例

package io;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;public class EnCodeStream {/** * @param args */public static void main(String[] args)throws IOException{writeTest();readText();}public static void readText()throws IOException{InputStreamReader isr=new InputStreamReader(new FileInputStream("file\\gbk.txt"),"UTF-8");char [] buf=new char[10];int len=isr.read(buf);String str=new String(buf,0,len);sop(str);isr.close();}public static void writeTest()throws IOException{OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream("file\\gbk.txt"),"UTF-8");osw.write("啦啦啦");osw.close();}public static void sop(Object obj){System.out.println(obj);}}


17、实例:

a) 需求:

有五个学生,每个学生有三门课的成绩,从键盘输入数据(姓名,三门课成绩),

输入格式:张三,899978

计算出总成绩,并把学生的信息和计算出的总分数按高低顺序存放在磁盘文件中

b) 思想

i. 通过获取键盘录入一行数据,并将改行中的信息取出封装成学生对象

ii. 因为学生有很多,那么就需要存储使用到集合,因为要对学生总分排序,使用TreeSet集合。

iii. 将集合的信息写入到一个文件中。

c) 代码实现

package io;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileWriter;import java.io.IOException;import java.io.InputStreamReader;import java.util.Collections;import java.util.Comparator;import java.util.Set;import java.util.TreeSet;public class StudentInfoTest {public static void main(String [] args)throws IOException{//定义一个反转顺序的比较器Comparator<Student> cmp=Collections.reverseOrder();//定义一个集合存储学生对象TreeSet<Student> stus=StudentInfoTool.getStudents(cmp);//将集合中数据写入文件StudentInfoTool.write2File(stus);}}//操作学生的工具class StudentInfoTool{//获取学生public static TreeSet<Student> getStudents()throws IOException{return getStudents(null);}//获取学生public static TreeSet<Student> getStudents(Comparator<Student> cmp)throws IOException{BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));String line=null;TreeSet<Student> stus=null;if(cmp==null)stus=new TreeSet<Student>();elsestus=new TreeSet<Student>(cmp);while((line=bufr.readLine())!=null){if("over".equals(line)) break;String[] infor=line.split(",");Student stu=new Student(infor[0],Integer.parseInt(infor[1]),Integer.parseInt(infor[2]),Integer.parseInt(infor[3]));stus.add(stu);}bufr.close();return stus;}//将集合中数据写入文件public static void write2File(TreeSet <Student> stus)throws IOException{BufferedWriter bufw=new BufferedWriter(new FileWriter("file\\studentInfor.txt"));for(Student stu:stus){bufw.write(stu.toString()+"\t");bufw.write(stu.getSum()+"");bufw.newLine();bufw.flush();}bufw.close();}}//学生类class Student implements Comparable<Student>{private String name;private int age,math,chinese,english,sum;Student(String name,int math,int chinese,int english){this.name=name;this.math=math;this.chinese=chinese;this.english=english;sum=math+chinese+english;}public int compareTo(Student s){int num=new Integer(this.sum).compareTo(new Integer(s.sum));if(sum==0)return this.name.compareTo(s.name);return sum;}public String getName(){return name;}public int getSum(){return sum;}public int hashCode(){return name.hashCode()+sum*87;}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+","+math+","+chinese+","+english+"]";}}



 

 

 

 

 

 

 

0 0