黑马程序员_IO流扩展

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

 

IO流管道流

import java.io.*;

class Piped //IO流管道流  注意:集合中涉及IO流的是Properties  在IO流中涉及多线程的管道流

{

         publicstatic void main(String[] args) throws Exception

         {

                   PipedInputStreamin = new PipedInputStream();

                   PipedOutputStreamout = new PipedOutputStream();

                   in.connect(out);                          //连接管道流

                   Readr = new Read(in);

                   Writew = new Write(out);

                   newThread(r).start();               //3.4.5

                   newThread(w).start();  

                  

                   //System.out.println("HelloWorld!");

         }

}

/*

创建多线程方式:第一种 继承Thread类 extends

1.继承Thread类

2.覆盖Thread类的run()方法

3.调用线程的start()方法

 

创建多线程方式:第一种 实现Runnable接口 implements

1.定义实现Runnable接口

2.覆盖Runnable接口中的run()方法

3.通过Thread类建立线程对象

4.将Runnable接口中的子类对象作为实际参数传递给Thread类的构造函数

5.调用Thread类的start()方法并调用Runnable的run方法

 

2种线程的区别:

实现方式的好处是避免了单继承的局限性,在定义线程时,建立使用实现方式

 

2种线程方式的区别:

继承Thread类:线程的代码存放到Thread子类run()方法中

实现Runnable类:线程代码存在接口的子类Run()方法中

*/

class Read implements Runnable  //1.定义实现Runnable接口

{

         privatePipedInputStream in ;

         Read(PipedInputStreamin )

         {

                   this.in= in ;

         }

         publicvoid run()                          //2.覆盖Runnable接口中的run()方法

         {

                   try

                   {

                            byte[]buf = new byte[1024];

                            System.out.println("读取前没有数据阻塞");

                            intlen = in.read(buf);

                            System.out.println("读取数据。。。阻塞结束");

                            Strings = new String(buf,0,len);

                            System.out.println(s);

                            in.close();

                   }

                   catch(Exception e)

                   {

                            thrownew RuntimeException("管道流读取失败");

                   }

         }

}

class Write implements Runnable

{

         privatePipedOutputStream out;

         Write(PipedOutputStreamout)

         {

                   this.out= out;

         }

         publicvoid run()

         {

                   try

                   {

                            System.out.println("开始输入数据等待6秒");

                            Thread.sleep(6000);                            

                            out.write("Piped".getBytes());//字节流??????

                            out.close();

                   }

                   catch(Exception e)

                   {

                            thrownew RuntimeException("管道流输出失败");

                   }

         }

}

/*

Throw的用法:定义在函数内用于抛出对象

Throws的用法:定义在函数上,用于抛出异常类,可以抛出多个用逗号隔开

当函数内有throw抛出异常对象并未进行try异常处理,必须在函数上声明,否则编译失败

注意:RuntimeException异常除外。也就是说函数内如果抛出的是RuntimeException异常,函数上可以不用声明。

 

如果函数声明了异常,调用者需要进行处理。处理方式可以throws可以try。

异常有2种:编译时被检测异常;运行时异常(编译时不检测)

异常的处理语句有3种格式:

 

异常的处理原则:(1)处理方式有2种,try或者throws;(2)调用到抛出异常的功能时,抛出几个就处理几个,即可能出现一个try对应多个catch的情况;(3)多个catch,父类的catch在最下面;

异常的注意事项:最常见的就是子父类覆盖时(1)子类抛出的异常必须是父类异常的子类或者子集(2)如果父类或者接口没有异常抛出时,子类覆盖出现异常只能try不能抛。

*/


IO流对象流的序列化

import java.io.*;

class obj //IO流————对象流的序列化

{

         publicstatic void main(String[] args) throws Exception

         {

                   writrObj();

                   //readObj();

                   //System.out.println("HelloWorld!");

         }

         publicstatic void writrObj()throws IOException//未报告的异常错误ClassNotFoundException 如果文件里,没有存储对象存储其他则返回不了对象

         {

                   ObjectOutputStreamoos =

                            newObjectOutputStream(new FileOutputStream("obj.txt")); //IO流————对象流的序列化

                   oos.writeObject(newPerson("li",20));

                   oos.close();

         }

         publicstatic void readObj()throws Exception//ObjectOutputStream 与ObjectInputStream是成对使用的

         {

                   ObjectInputStreamois =

                            newObjectInputStream(new FileInputStream("obj.txt"));//IO流————对象流的序列化

                   Personp = (Person)ois.readObject();

                   System.out.println(p);

                   ois.close();

         }

}

class Person implementsSerializable//java.io.NotSerializableException: Person

{

         publicstatic final long serialVersionUID = 42L; //用于给类进行定义标记用的

   private String name;

         intage;                       //非静态成员不想被序列化的话需要加上关键字transient int age;

         staticString s = cn;//静态不能被序列化

         Person(Stringname,int age)             /

         {

                   this.name= name;

                   this.age= age;

         }

         publicString toString()

         {

                   returnname +"...."+age;

         }

}

 

IO流中转换流的字符编码————(字符流的出现时为了操作字符数据的)

//ASCII ISO8859-1  GB2312  GBK  UTF-8  Unicode

import java.io.*;

class EncodeStream

{

         publicstatic void main(String[] args)throws IOException

         {

                   //System.out.println("HelloWorld!");

                   //writeText();

                   readText();

         }

         publicstatic void writeText()throws IOException

         {

                   OutputStreamWriterosw =

                            newOutputStreamWriter(newFileOutputStream("utf.txt"),"UTF-8");//改成UTF-8 6个字节    

                            //newOutputStreamWriter(newFileOutputStream("gbk.txt"),"GBK");//默认GBK 4个字节

                   osw.write("你好");

                   osw.close();

         }

         publicstatic void readText()throws IOException

         {

                   InputStreamReaderisr =

                            //newInputStreamReader(new FileInputStream("gbk.txt"),"GBK");//结果为你好

                            //newInputStreamReader(newFileInputStream("gbk.txt"),"UTF-8");//结果为??(未知字符)

                            newInputStreamReader(newFileInputStream("utf.txt"),"UTF-8");//结果为你好

                           

                            //总结:结果是??说明用GBK编码用UTF-8解码  结果是浣扐说明用UTF-8编码用GBK解码

 

                   char[]buf = new char[10];

                   intlen= isr.read(buf);

                   Strings = new String(buf,0,len);

                   System.out.println(s);

                   isr.close();

         }

}


//注意关闭ByteArrayInputStream无效,此类方法总关闭此流后仍可以被调用,而不会产生任何IOException

//ByteArrayInputStream 与 ByteArrayOutputStream这两个流对象都是操作数组的,并没有使用系统资源,所以不进行close()关闭;

 

import java.io.*;

class ByteStream

{

         publicstatic void main(String[] args)

         {

                   //数据源

                   ByteArrayInputStreambis = new ByteArrayInputStream("ABC".getBytes());//源是数组

                   //数据目的

                   ByteArrayOutputStreambos = new ByteArrayOutputStream();

                   intby = 0;

                   while((by=bis.read())!=-1)

                   {

                            bos.write(by);

                   }

                   System.out.println(bos.size());

                   System.out.println(bos.toString());

                   bos.writeTo(newFileOutputStream("a.txt"));//将数组输出的流全部内容写入到指定的输出流参数中

         }

}

/*

         用流的读写来操作数组

 

         原设备:键盘 System.in   硬盘 FileStream   内存 ArrayStream    

         目的设备;控制台 System.out 硬盘 FileStream  内存 ArrayStream

         对数组的操作有2种情况,设置角标和获取角标

 

         操作字符数组

         CharArrayReader与CharArrayWrite

 

         操作字符串

         StringReader与StringWriter

 

         现在想把一个(硬盘)文件读写到(内存)中,放到一个数组中存起来

*/

 

RandomAccessFile

不是IO体系中的子类,而是直接继承Object,但它是IO包中的一员(具备读写功能)

//内部封装一个数组,通过指针(getFilePointer获取指针位置,通过seek改变指针的位置)对数组的元素进行操作

//通过构造函数看出该类只能操作文件,而文件有模式:只读r、读写rw等

 

//多线程等下载操作都是基于此方法,重点掌握:1.模式 2.基本数据类型 3.通过seek方法改变指针的位置

 

import java.io.*;

class RandomF                   //很重要!!!

{

         publicstatic void main(String[] args) throws IOException

         {

                   //writeFile();

                   //readFile();

 

                   //注意:可以随机的读和写,流在操作数据的时候只能按照顺序,

                   writeFile_2();

         }

         publicstatic void writeFile() throws IOException

         {

                   RandomAccessFiler = new RandomAccessFile("1.txt","rw");

                   r.write("李四".getBytes());

                   //s.write(97);            //数据丢失!!!

                   r.writeInt(90);           //并且每次结果都在修改

                   r.write("王五".getBytes());

                   r.writeInt(99); 

                   r.close();

         }

         publicstatic void readFile() throws IOException

         {

                   RandomAccessFilew = new RandomAccessFile("1.txt","r");

                   //r.write("王五".getBytes());  //报错,愿意"r"是只读

                  

                   /*

                   byte[]buf = new byte[4];

                   w.read(buf);

                   Stringname = new String(buf);

                   intage = w.readInt();       //读取一个32位整数

                   System.out.println("name=..."+name);

                   System.out.println("age=..."+age);                 

                   w.close();

                   */

 

                   //==================关键====================//

                   //现在只想取王五

                   //w.skipBytes(8);     //跳过的指定字节数

                  

                   w.seek(8*0);             //调整对象中的指针

                   byte[]buf = new byte[4];

                   w.read(buf);

                   Stringname = new String(buf);

                   intage = w.readInt();       //读取一个32位整数

                   System.out.println("name=..."+name);

                   System.out.println("age=..."+age);                 

                   w.close();

         }

                   publicstatic void writeFile_2() throws IOException

                   {

                            RandomAccessFilew1 = new RandomAccessFile("1.txt","rw");//想要实现第四个位置是周期

                            w1.seek(8*3);

                            w1.write("周期".getBytes());

                            w1.writeInt(19);

                            w1.close();

                   }

}

 

/*

以下功能注意,不要混淆

File对象功能——获取:getName(); getPath(); getParent(); getAbsolutePath();lastModified(); length();

 

于第十八天其他对象的区别  Math-Random:

double d = Math.ceil(12.34);            //返回大于数据的最小整数

double d = Math.floor(12.34);          //返回小于数据的最大整数

double d = Math.round(12.34);                 //四舍五入

double d = Math.pow(2,3);                         //密数次米

double d = (int)(Math.random()*10+1);//随机数

 

基本数据类型转成字符串:基本数据类型.toString(基本数据类型值)

                                                        如:Integer.toString(34);

字符串转成基本数据类型:xxx a =xxx.parsexxx(string)

                                                        如:int a = Integer.parseint("123")

*/

---------------------- <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、付费专栏及课程。

余额充值