JAVA笔记-14

来源:互联网 发布:神奇网络热血霸业下载 编辑:程序博客网 时间:2024/06/16 02:52

1.每次读取一行:LineNumberReader


 

//1.封装数据源和目的地FileReader fr=new FileReader("a.txt");FileWriter fw=new FileWriter("f.txt");//2.1一次读写一个字符//int ch;//while((ch=fr.read())!=-1){//fw.write(ch);//fw.flush();//}//2.2 一次读写一个字符数组char[] chs=new char[1024];int len;while((len=fr.read(chs))!=-1){fw.write(chs,0,len);fw.flush();}//3.关流fw.close();fr.close();}



2.操作基本数据类型流对象

 DataInputStream dis = new DataInputStream(new FileInputStream("dos.txt"));

 DataOutputStream dos = new DataOutputStream(new FileOutputStream("dos.txt"));

       

以什么数据写入,以什么数据读出,按顺序


3.将写入内存中的流转换成字节数组

ByteArrayOutputStream baos = new ByteArrayOutputStream();

baos.write("hello".getBytes());

byte[] buf = baos.toByteArray();//调用这个方法,将之前写入内存中的数据存储到字节数组中
ByteArrayInputStream bais = new ByteArrayInputStream(buf);//将刚才存储到字节数组中的内容关联上bais

int by;
while ((by=bais.read())!=-1) {
System.out.print((char)by);
}
//关流
bais.close();
baos.close();


4.打印流:

        字节打印流PrintStream

  字符打印流PrintWriter

 

特 点: 1.只能操作目的地,不能操作数据源

             2.可以操作任意类型的数据

             3.启动自动刷新,可以自动刷新

               创建字符打印流对象,并开启自动刷新

    PrintWriter pw=new PrintWriter(new FileWriter("pw2.txt"),true);

          可操作任意类型的数据,刷新必须用println,printf,format

                pw.println("hello");

pw.println(true);

pw.println(12.34);

                pw.close();


  5.合并流    

    SequenceInputStream(InputStream s1, InputStream s2)

    先读s1,在读s2


   6.序列化反序列化:要有一个类实现Serializable接口才行

   序列化:将对象按照流的方式写到文件或者网络中传输

   反序列化:把文件或网络中的流对象数据还原为对象

    ObjectOutputStream:序列化流

     ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("oos.txt"));

      Studnet s = new Studnet("刘德华", 50);

      oos.writeObject(s);

      oos.close();


      ObjectInputStream:反序列化流

     ObjectInputStream ois = new ObjectInputStream(new FileInputStream("oos.txt"));

      Object object = ois.readObject();
      System.out.println(object);

      ois.close();


    7.Properties

  1. A:添加元素
  public Object setProperty(String key,String value)
          B:获取元素
   public String getProperty(String key)


           //创建Properties这个集合
Properties prop = new Properties();

//调用public Object setProperty(String key,String value)
prop.setProperty("huangxiaoming", "baby");
prop.setProperty("dengchao", "sunli");
prop.setProperty("xidada", "pengliyuan");

//1.获取所有键的集合
//public Set<String> stringPropertyNames()
Set<String> keys = prop.stringPropertyNames();
//遍历键,根据键找值
for (String key : keys) {
        System.out.println(key+":"+prop.getProperty(key));

    

     2.将文件中的数据加载到集合中,数据必须为键值对形式

      Properties prop = new Properties();

    prop.load(new FileReader("prop"));

        





原创粉丝点击