黑马程序员_IO流字节流

---------------------- <a href="http://www.itheima.com"target="blank">ASP.Net+Unity开发</a>、<a href="http://www.itheima.com"target="blank">.Net培训</a>、期待与您交流! ----------------------

IO流

InputStream  OutputStream

//字节流的File操作!!!重点

import java.io.*;

class FileStream

{

         publicstatic void main(String[] args) throws IOException

         {

                   readStream_3();

         }

         publicstatic void writeStream() throws IOException

         {

                   //字节不具备刷新功能,但必须关闭资源

                   FileOutputStreams = new FileOutputStream("123.txt",true);

                   s.write("asssd122".getBytes());

                   s.close();

         }

         publicstatic void readStream_1() throws IOException

         {

                   //单个读

                   FileInputStreamd = new FileInputStream("123.txt");

                   intch =0;

                   while((ch = d.read())!=-1)

                   {

                            System.out.println((char)ch);

                   }

                   d.close();

         }

         publicstatic void readStream_2() throws IOException

         {

                   //一起读

                   FileInputStreamz = new FileInputStream("123.text");

                   byte[]buf = new byte[1024];

                   intlen = 0;

                   while((len = z.read(buf))!=-1)

                   {

                            System.out.println(newString(buf,0,len));

                   }

                   z.close();

         }

         publicstatic void readStream_3() throws IOException

         {

                   //字节流特有

                   FileInputStreame = new FileInputStream("123.text");

                   intnum = e.available();

                   System.out.println(num);

                   e.close();

         }

         publicstatic void readStream_3() throws IOException

         {

                   //不用在循环

                   FileInputStreamz = new FileInputStream("123.text");

                   byte[]buf = new byte[z.available()];//定义一个刚刚好的缓冲区,不需要循环了

                   z.read(buf)

                   System.out.println(newString(buf));

                   z.close();

         }

}

 

通过明确来完成。

(1)、明确源和目的

源:输入流InputStream Reader

目的:输出流OutputStream Writer

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

是:字符流 Reader Writer

不是:字节流 InputStream OutputStream

(3)、当体系明确后,再明确要使用那个具体的对象

通过设备来进行区分:

源设备:内存 硬盘 键盘

目的设备:内存 硬盘 控制台

 

需求一:(1)将一个文本文件中数据存储到另一个文件中。复制文件

源:因为是源,所以使用读取流。InputStream Reader

是否是纯文本文件:是,所以使用 Reader。

接下来明确要使用该体系中的那个对象:

明确设备,硬盘,一个文件。

              Reader体系中可以操作文件的是,FileReader。

是否需要提高效率? BufferedReader

 

(2)目的:因为是目的,所以使用写入流。OutputStreamWriter

是否是纯文本文件:是,所以使用 Writer。

明确目的,硬盘,一个文件。

Writer 体系中可以操作文件的是,FileWriter。

是否需要提高效率?需要。BufferedWriter

      

需求二:(1)将键盘录入的数据保存到一个文件中

源:因为是源,所以使用读取流。InputStream Reader

是否是纯文本文件:是,所以使用 Reader。

明确设备,键盘。对应的对象是System.in。

不是选择Reader吗?System.in 对应的不是字节流吗?

为了操作键盘的文字数据方便,字节流可以转换成字符流,按照字符串操作最方便。

既然明确了Reader 就将 System.in 转换成Reader

用到了Reader 体系中的转换流,InputSteamReader

需要提高效率吗?需要,BufferedReader

 

(2)目的:因为是目的,所以使用写入流。OutputStreamWriter

是否是纯文本文件:是,所以使用 Writer。

明确目的,硬盘,一个文件。

Writer 体系中可以操作文件的是,FileWriter。

是否需要提高效率?需要。BufferedWriter

 

扩展一:想要把录入的数据按照指定的编码表(UTF-8),将数据存到文件中,使用转换流,里面可以指定编码。

目的:OutputStream Writer         是否是纯文本?是,Writer

明确目的,硬盘,一个文件。Writer 体系中可以操作文件的是,FileWriter。

但是存储时,需要加入指定的编码表,而指定的编码表,只有转换流可以指定。

所以要使用的对象是OutputStreamWriter.

而该转换流对象要接收一个字节输出流。

而且还可以操作文件的字节输出流,FileOutputStream

是否需要提高效率?需要。BufferedWriter

所以,记住,转化暖流什么时候使用,字符和字节之间的桥梁,通常,涉及到字符编码转换时,需要用到转换流。

IO流(改变标准输入输出设备)

 

//复制一个图片

//注意:不要用字符流去拷贝媒体文件,字符流使用来处理文字数据的

import java.io.*;

class CopyPic

{

         publicstatic void main(String[] args) throws IOException

         {

                   /*方法1

                   FileOutputStreamou = new FileOutputStream("C:\\.2.jpg");

                   FileInputStreamin = new FileInputStream("C:\\1.jpg");

                   intnum = 0;

                   while((num = in.read())!=-1)

                   {

                            ou.write(num);

                   }

                   ou.close();

                   in.close();

                   */

 

                   //方法2

                   FileOutputStreamou = new FileOutputStream("C:\\.2.jpg");

                   FileInputStreamin = new FileInputStream("C:\\1.jpg");

                   byte[]bvf = new byte[in.available()];

                   in.read(bvf);

                   ou.write(bvf);

                   ou.close();

                   in.close();

 

                   /*方法3

                   FileOutputStreamou = null;

                   FileInputStreamin = null;

                   try

                   {

                            ou= new FileOutputStream("c:\\.2.jpg");

                            in= new FileInputStream("c:\\1.jpg");

                           

                            //byte[]bvf = new byte[1024];

                            //intlen = 0;

                            //while((len= in.read(bvf))!=-1)

                            //{

                            //      ou.write(bvf,0,len);

                            //}

                           

                            byte[]bvf = new byte[in.available()];

                            in.read(bvf);

                            ou.write(bvf);          

                   }

                   catch(Exception e)

                   {

                            thrownew RuntimeException("复制失败");

                   }

                   finally

                   {

                            if(in!=null)

                            try

                            {

                                     in.close();

                            }

                            catch(Exception e)

                            {

                                     thrownew RuntimeException("读取失败");

                            }

                            if(ou!=null)

                            try

                            {

                                     ou.close();

                            }

                            catch(Exception e)

                            {

                                     thrownew RuntimeException("写入失败");

                            }

                   }

                   */

         }

}

 

//复制一个音频文件

//注意:不要用字符流去拷贝媒体文件,字符流使用来处理文字数据的

import java.io.*;

class CopyM

{

         publicstatic void main(String[] args) throws IOException

         {

                   /*方法1

                   FileOutputStreamou = new FileOutputStream("C:\\.2.jpg");

                   FileInputStreamin = new FileInputStream("C:\\1.jpg");

                   intnum = 0;

                   while((num = in.read())!=-1)

                   {

                            ou.write(num);

                   }

                   ou.close();

                   in.close();

                   */

 

                   //方法2

                   BufferedOutputStreamou = new BufferedOutputStream(new FileOutputStream("C:\\a.mp4"));

                   BufferedInputStreamin = new BufferedInputStream(new FileInputStream("C:\\s.mp4"));

                   byte[]bvf = new byte[in.available()];

                   in.read(bvf);

                   ou.write(bvf);

                  

                   ou.close();

                   in.close();

         }

}


import java.io.*;

class ReadIn

{

         publicstatic void main(String[] args) throws IOException

         {

                   //键盘录入

                   //System.out:对应的是标准输出设备

                   //System.in      :对应的是标准的输入设备

                   //InputStreamin = System.in;

                   //intby = in.read();

                   //System.out.println(by);//r-13 n-10 1-49 1-97

 

                   //需求,(1)通过键盘录入数据,录入后一行就打印,如果结果为over那么就停止

                   /*

                   InputStreamin = System.in;

                   StringBuffersb = new StringBuffer();

                   while(true)

                   {

                            intch = in.read();

                            if(ch=='\r')

                                     continue;

                            if(ch=='\n')

                            {

                                     Strings = sb.toString();

                                     if("over".equals(s))

                                               break;

                                     System.out.println(s);

                                     sb.delete(0,sb.length());//清空缓冲区

                            }

                            else

                                     sb.append((char)ch);

                   }

                   */

              

                   //(2)同样的要求,操作方法是将字节流转换成字符流

                   //InputStreamReaderOutputStreamWriter

                   InputStreamin = System.in;

                   InputStreamReaders = new InputStreamReader(in);

                   BufferedReaderbuf = new BufferedReader(s);

                   //BufferedReaderbuf = new BufferedReader(new InputStreamReader(System.in));

                   Stringline = null;

                   while((line = buf.readLine())!=null)

                   {

                            if("over".equals(line))

                                     break;

                            System.out.println(line);

                   }

                   buf.close();                     

         }

}

 

/*

练习:有5个学生,每个学生有3门课程的成绩,

从键盘录入以上数据(包括姓名、三门课程的成绩),

输入的格式如:张三,20,30,40并计算出总成绩

并把学生的信息和计算出的总分数高低顺序存放在存盘文件"stud.txt"中

*/

import java.io.*;

import java.util.*;

class St

{

         publicstatic void main(String[] args) throws IOException// 未报告的异常错误IOException

         {

                   Set<Student>stus = StuTool.getStu();

                   StuTool.write2File(stus);

         }

}

 

class StuTool

{

         publicstatic Set<Student> getStu() throws IOException

         {

                   BufferedReaderbufr =

                            newBufferedReader(new InputStreamReader(System.in));//对于FileInputStream(InputStream), 找不到合适的构造器 new BufferedReader(new FileInputStream(System.in));

                   Stringline = null;

                   Set<Student>stus = new TreeSet<Student>();

                   while((line = bufr.readLine())!= null)

                   {

                            if("over".equals(line))

                                     break;

                            String[]info = line.split(",");

                            Studentstu = new Student(info[0],Integer.parseInt(info[1]),

                                      Integer.parseInt(info[2]),

                                      Integer.parseInt(info[3]));

                            stus.add(stu);

                   }

                   bufr.close();

                   returnstus;

         }

         publicstatic void write2File(Set<Student> stus) throws IOException

         {

                   BufferedWriterbufw =new BufferedWriter(new FileWriter("stud.txt"));

                   for(Student stu :stus)

                   {

                            bufw.write(stu.toString()+"\t");//stu.getName()

                            bufw.write(stu.getSum()+"");

                            bufw.newLine();

                            bufw.flush();

                   }

                   bufw.close();

         }

}

 

class Student implementsComparable<Student>

{

         privateString name;

         privateint ma;

         privateint cn;

         privateint en;

         privateint sum;

         Student(Stringname,int ma,int cn,int en)

         {

                   this.name= name;

                   this.ma= ma ;

                   this.cn= cn;

                   this.en= en;

                   sum= ma +en +cn;//.java:65: 错误: 找不到符号 sum没定义

         }

         publicString getName()//对于结果类型为空的方法, 无法返回值所以用String 而不是void

         {

                   returnname;

         }

         publicint getSum()

         {

                   returnsum;

         }

         publicint hashCode()

         {

                   returnname.hashCode()+sum*37;

         }

         publicboolean equals(Object obj)//boolean要小写

         {

                   if(!(objinstanceof Student))

                             throw new ClassCastException("类型不匹配");

                   Studentp = (Student)obj;

                   returnthis.name.equals(p.name) && this.sum==p.sum;

         }

         publicint compareTo(Student s )

         {

                   intnum = new Integer(this.sum).compareTo(new Integer(s.sum));//注意compareTo的大小写

                   if(num==0)

                            returnthis.name.compareTo(s.name);

                   returnnum;

         }

         publicString toString()

         {

                   return"Student=" + name+","+ ma +"," + cn+"," + en;

         }

 

}

---------------------- <a href="http://www.itheima.com"target="blank">ASP.Net+Unity开发</a>、<a href="http://www.itheima.com"target="blank">.Net培训</a>、期待与您交流! ----------------------

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值