java-sec6

1.Map

Hashmap HashTable TreeMap

HashMap

最常用的Map,它根据键的HashCode 值存储数据,根据键可以直接获取它的值,具有很快的访问速度。HashMap最多只允许一条记录的键为Null(多条会覆盖);允许多条记录的值为 Null。非同步的。

TreeMap

能够把它保存的记录根据键(key)排序,默认是按升序排序,也可以指定排序的比较器,当用Iterator 遍历TreeMap时,得到的记录是排过序的。TreeMap不允许key的值为null。非同步的。 
Hashtable

Hashtable

与 HashMap类似,不同的是:key和value的值均不允许为null;它支持线程的同步,即任一时刻只有一个线程能写Hashtable,因此也导致了Hashtale在写入时会比较慢。 


初始化

Map<K key,V value>=new HashMap<K,V>();

map.put();

map.get();

map.remove();

map.clear(); 

常用API

Interator interator()

boolean hashnext()

keySet()  返回 Map 中所包含键的 Set 视图。删除 Set 中的元素还将删除 Map 中相应的映射(键和值)

使用keySet遍历

for  (String key : map.keySet()) {
     System.out.println(key +  " :"  + map.get(key));
}

迭代器遍历

Iterator<String> iterator = map.keySet().iterator();
while  (iterator.hasNext()) {
     String key = iterator.next();
     System.out.println(key +  " :"  + map.get(key));
}


i/o编程

  IuputStream的方法

   int read(): 一次读一个字节

   int read(byte[]) :读多个字节到数组中

   int read(byte[],int off,int len) :指定从数组的哪里开始,读多长

   mark() :在流中标记一个位置,要与markSupported()连用

   reset() :返回标记过的位置write(int) :写一个字节到流中

  OutputStream的方法

    write(int) :写一个字节到流中

    write(byte[]): 将数组中的内容写到流中

    write(byte[],int off,int len): 将数组中从off指定的位置开始len长度的数据写到流中

   close() :关闭流

   flush() :将缓冲区中的数据强制输出

  文件流

  1. import java.io.*;  
  2. public class Copy{  
  3. public static void main(String args[]){  
  4.      FileInputStream fis=null;  
  5.      FileOutputStream fos=null;  
  6.      try{  
  7.         fis=new FileInputStream("c2.gif");  
  8.         fos=new FileOutputStream("c2_copy.gif");  
  9.         int c;  
  10.         while((c=fis.read()) != -1)  
  11.             fos.write(c);  
  12.         }catch(Exception e){  
  13.             e.printStackTrace();  
  14.         }finally{  
  15.             if(fis != nulltry{ fis.close(); }catch(Exception e){ e.printStackTrace(); }  
  16.             if(fos!= nulltry{ fos.close(); }catch(Exception e){ e.printStackTrace(); }  
  17.         }  
  18.     }  
  19. }

    对象流:能够输入输出对象的流

    串行化:对象通过写出描述自己状态的数值来记述自己的过程叫串行话
    对象流:能够输入输出对象的流
    将串行化的对象通过对象流写入文件或传送到其他地方
    对象流是在普通流上加了传输对象的功能,所以构造对象流时要先构造普通文件流

    注意:只有实现了Serializable接口的类才能被串行化


  1. import java.io.*;  
  2. class Student implements Serializable{  
  3.     private String name;  
  4.     private int age;  
  5.   
  6.     public Student(String name,int age){  
  7.          this.name=name;  
  8.          this.age=age;  
  9.      }  
  10.   
  11.      public void greeting(){  
  12.           System.out.println("hello ,my name is "+name);  
  13.      }  
  14.   
  15.      public String toString(){  
  16.           return "Student["+name+","+age+"]";  
  17.    }  
  18. }

    

  1. public class ObjectOutTest{  
  2.       public static void main(String args[]){  
  3.       ObjectOutputStream oos=null;  
  4.       try{  
  5.          oos=new ObjectOutputStream(new FileOutputStream("student.txt"));  
  6.          Student s1=new Student("Jerry",24);  
  7.          Student s2=new Student("Andy",33);  
  8.   
  9.          oos.writeObject(s1);  
  10.          oos.writeObject(s2);  
  11.         }catch(Exception e){  
  12.              e.printStackTrace();  
  13.         }finally{  
  14.              if(oos!=null)  
  15.              try{  
  16.                 oos.close();  
  17.               }catch(Exception e){  
  18.                    e.printStackTrace();  
  19.              }  
  20.           }  
  21.      }  
  22. }

  1. import java.io.*;  
  2. public class ObjectInTest{  
  3.        public static void main(String args[]){  
  4.        ObjectInputStream ois=null;  
  5.        Student s=null;  
  6.        try{  
  7.          ois=new ObjectInputStream(  
  8.          new FileInputStream("student.txt"));  
  9.          System.out.println("--------------------");  
  10.          s=(Student)ois.readObject();  
  11.          System.out.println(s);  
  12.          s.greeting();  
  13.          System.out.println("--------------------");  
  14.          s=(Student)ois.readObject();  
  15.          System.out.println(s);  
  16.          s.greeting();  
  17.         }catch(Exception e){  
  18.             e.printStackTrace();  
  19.         }finally{  
  20.             if(ois!=null)  
  21.             try{  
  22.               ois.close();  
  23.             }catch(Exception e){  
  24.              e.printStackTrace();  
  25.           }  
  26.        }  
  27.     }  


     随机存储文件 RandomAccessFile

     可同时完成读写操作 / 支持随机文件操作的方法:readXXX() / writeXXX()seek() 将指针调到所需位置
      getFilePointer() 返回指针当前位置 / length() 返回文件长度

     

  1. import java.io.*;  
  2. public class RandomFile{  
  3.    public static void main(String args[]){  
  4.         RandomAccessFile raf=null;  
  5.         int data[]={12,31,56,23,27,1,43,65,4,99};  
  6.         try{  
  7.            raf=new RandomAccessFile("temp.txt","rw");  
  8.            for(int i=0;i<data.length;i++)  
  9.                 raf.writeInt(data<i>);  
  10.                 for(int i=data.length-1;i>=0;i--){  
  11.                      raf.seek(i*4);  
  12.                      System.out.println(raf.readInt());  
  13.                 }  
  14.            }catch(Exception e){  
  15.                e.getMessage();  
  16.            }finally{  
  17.                if(raf!=null)  
  18.                try{  
  19.                   raf.close();  
  20.               }catch(Exception e){  
  21.                  e.getMessage();  
  22.             }  
  23.        }  
  24.    }  
  25. }

   

字节流:

InputStream
|-- FileInputStream (基本文件流)
|-- BufferedInputStream
|-- DataInputStream
|-- ObjectInputStream
OutputStream 同上图
BufferedInputStream DataInputStream ObjectInputStream 只是在 FileInputStream 上增添了相应的功能,构造时先构造FileInputStream

 字符流:
Reader
|-- InputStreamReader (byte->char 桥梁)
|-- BufferedReader (常用)

Writer
|-- OutputStreamWriter (char->byte 桥梁)
|-- BufferedWriter
|-- PrintWriter (常用)

 随机存取文件 RandomAccessFile

引用:https://www.cnblogs.com/dongguacai/p/5656471.html

File类

1、一个File类的对象,表示磁盘上的文件或目录。

2、File提供了与平台无关的方法来对磁盘上的文件或目录进行操作。

3、File类直接处理文件和文件系统。

4、File类没有指定信息怎样从文件读取或向文件存储。


 1 package io;
 2 
 3 import java.io.File;
 4 import java.io.IOException;
 5 
 6 public class FileTest
 7 {
 8     public static void main(String[] args) throws IOException
 9     {
10         File file = new File("f:/migu");
11         file.mkdir();  //只能在已经存在的文件夹下创建新的文件夹,且只能建立一级的文件夹
12         //判断该抽象名表示的目录是否存在
13         if(file.exists() && file.isDirectory())
14         {
15             System.out.println("migu 目录存在");
16             File file1 = new File("f:/migu/UES.txt");
17             File file2 = new File("f:\\migu\\CMU.txt");
18             //创建文件
19             file1.createNewFile();
20             file2.createNewFile();
21             File file3 = new File("f:/migu/插件/支付中心");
22             //创建此抽象名表示的目录,以及所有必需但是不存在的父目录
23             file3.mkdirs();
24             File[] files = file.listFiles();
25             //该方法返回该路径下这一层的所有文件和目录
26             for(File f : files)
27             {
28                 System.out.println("migu目录下的文件名:" + f.getName());
29                 System.out.println("migu目录文件的绝对路径:" + f.getAbsolutePath());
30             }
31         }
32         else
33         {
34             System.out.println("migu 目录不存在");
35         }
36         
37     }
38 }
结果:
 
migu 目录存在
migu目录下的文件名:CMU.txt
migu目录文件的绝对路径:f:\migu\CMU.txt
migu目录下的文件名:UES.txt
migu目录文件的绝对路径:f:\migu\UES.txt
migu目录下的文件名:插件
migu目录文件的绝对路径:f:\migu\插件


Java Properties类

读取Java的配置文件,各种语言都有自己所支持的配置文件,配置文件中很多变量是经常改变的,这样做也是为了方便用户,让用户能够脱离程序本身去修改相关的变量设置。

继承自Hashtable

它提供了几个主要的方法:

1. getProperty ( String key),用指定的键在此属性列表中搜索属性。也就是通过参数 key ,得到 key 所对应的 value。

2. load ( InputStream inStream),从输入流中读取属性列表(键和元素对)。通过对指定的文件(比如说上面的 test.properties 文件)进行装载来获取该文件中的所有键 - 值对。以供 getProperty ( String key) 来搜索。

3. setProperty ( String key, String value) ,调用 Hashtable 的方法 put 。他通过调用基类的put方法来设置 键 - 值对。

4. store ( OutputStream out, String comments),以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。

5. clear ()清除所有装载的 键 - 值对。该方法在基类中提供。

读取Properties方法 

InputStream in = new BufferedInputStream(new FileInputStream(name));

Properties p = new Properties();

InputStream in = getClass().getResourceAsStream("资源Name");

      public class TestProperties {
 3     //根据Key读取Value
 4     public static String GetValueByKey(String filePath, String key) {
 5         Properties pps = new Properties();
 6         try {
 7             InputStream in = new BufferedInputStream (new FileInputStream(filePath));  
 8             pps.load(in);
 9             String value = pps.getProperty(key);
10             System.out.println(key + " = " + value);
11             return value;
12             
13         }catch (IOException e) {
14             e.printStackTrace();
15             return null;
16         }
17     }
18     
19     //读取Properties的全部信息
20     public static void GetAllProperties(String filePath) throws IOException {
21         Properties pps = new Properties();
22         InputStream in = new BufferedInputStream(new FileInputStream(filePath));
23         pps.load(in);
24         Enumeration en = pps.propertyNames(); //得到配置文件的名字
25         
26         while(en.hasMoreElements()) {
27             String strKey = (String) en.nextElement();
28             String strValue = pps.getProperty(strKey);
29             System.out.println(strKey + "=" + strValue);
30         }
31         
32     }
33     
34     //写入Properties信息
35     public static void WriteProperties (String filePath, String pKey, String pValue) throws IOException {
36         Properties pps = new Properties();
37         
38         InputStream in = new FileInputStream(filePath);
39         //从输入流中读取属性列表(键和元素对) 
40         pps.load(in);
41         //调用 Hashtable 的方法 put。使用 getProperty 方法提供并行性。  
42         //强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。
43         OutputStream out = new FileOutputStream(filePath);
44         pps.setProperty(pKey, pValue);
45         //以适合使用 load 方法加载到 Properties 表中的格式,  
46         //将此 Properties 表中的属性列表(键和元素对)写入输出流  
47         pps.store(out, "Update " + pKey + " name");
48     }
49     
50     public static void main(String [] args) throws IOException{
51         //String value = GetValueByKey("Test.properties", "name");
52         //System.out.println(value);
53         //GetAllProperties("Test.properties");
54         WriteProperties("Test.properties","long", "212");
55     }
56 }

多线程

  • 通过实现 Runnable 接口;
  • 通过继承 Thread 类本身;
  • 通过 Callable 和 Future 创建线程。

synchronized public void push(char c){ } //线程同步

public char pop(){  synchronized(this) {} }

public char pop(){

while(index==0) //不应该使用if来进行判断

{  try { wait();} //对阻塞的条件判断用while

   catch(InterruptedException e){ e.printStackTrace();} 

}

 index--;

 notifyAll();

 return data[index]; 

}

synchronized public void push(char c){

while(index==data.length) //不应该使用if来进行判断

{  try { wait();} //对阻塞的条件判断用while

   catch(InterruptedException e){ e.printStackTrace();} 

}

data[index]=c; 

index++;

 notifyAll();

}


//主线程不结束不占用cpu资源

{  Thread t1=new EThread();

  Thread t2=new EThread();

  t1.seDaemon(true);

  ...

  //t1.join();

  ...

}


LinkBblockingQueue类 //实现阻塞机制

import java.io.*;

import java.util.*;

public static void main (String[] args)

 try {

   FileOutputStream fos=new FileOutputStream("a.dat");

   //FileOutputStream fos=new FileOutputStream("a.txt"); OutputStreamWriter osw= new OutputStreamWriter(fos,"GBK");

   DataOutputStream dos=new DataOutputStream(fos);

for(int i=0;i<10;i++){

dos.writeInt(i);

dos.writeDouble(Math.random());

dos.writeUTF("hello");

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值