IO笔记

来源:互联网 发布:中兴软件技术有限公司 编辑:程序博客网 时间:2024/04/28 10:21
1 System
1.1 I/O流
l public static InputStream in: 读取字符的标准输入流。
l public static PrintStream out: 标准输出流。
l public static PrintStream err: 标准错误输出流。
1.2  系统属性
   (1) 属性
l java.version 版本号       java.vendor销售商 
l java.vendor.url           java.home安装目录
l java.class.version类版本   java.class.path类路径
l os.name                  os.arch支持的体系结构
l os.version                file.separator
l path.separator            line.separator  行分隔符
l user.name                user.home    home目录
l user.dir 用户当前目录
   (2) 方法
l public static Properties getProperties(): 取系统属性。如果当前系统属性集不存在,则创建并初始化。
l public static void setProperties(Properties props)
l public static String getProperty(String key)
返回名为key的属性值。等效于System.getProperties().getProperty(key);
l public static String getProperty(String key,String defaultValue)
返回名为key的属性值。若没定义则返回defaultValue。它等效于System.getProperties().getProperty(key,def);

(3)  属性值的解码   属性值转换成数值(对象)
l static boolean Boolean.getBoolean(String name)
name为”true”(不区分大小写)时, 返回true,否则false
l static Integer Integer.getInteger(String name)
如果没有数字形式,返回null。
l static Integer Integer.getInteger(String name,Integer def): 如果没有数字形式,返回缺省值def
l static Long Long.getLong(String nm)
l static Long Long.getLong(String nm,Long def)
   (4) Eample
public static File personal(String fileName){
  String home = System.getProperty("user.home");
  if  (home == null)    return null;
  else  return new File(home,fileName);
}
1.3安全性
(1)  SecurityManager
l 抽象类,可实现各种安全策略
l 提供各种check方法控制是否能打开网络接口、是否允许文件存取、线程创建等
      (2) System与安全性
l static void setSecurityManager(SecurityManager s)
置系统安全管理对象。此值只能置一次。 以后无论谁启动系统安全机制都将取决于先前置的值而不能改变它。
l public static SecurityManager getSecurityManager()
1.4杂项
l public static long currentTimeMillis()
    返回以微秒为单位的GMT时间(按UTC标准从1970年1月1日的00:00:00 开始计时) 。在292280995年前它不会溢出. 如复杂情况可用Date类。
l public static void arraycopy(Object src,int srcPos,Object dst,int dstPos, int count)
    将源数组中src[srcPos]开始的count个元素拷贝到目的数组中以dst[dstPos]开始的相应元素中。

2 Runtime & Process
2.1 Runtime
l 每个应用程序对应一个Runtime实例,与运行环境相接
l 用getRuntime()方法获得: static Runtime getRuntime()
l 应用程序无法创建自己的Runtime类实例
2.2 内存管理
      (1) 有关方法
l public long freeMemory():返回可用内存字节数。
l public long totalMemory():返回总的内存字节数。
l void gc(): 使java虚拟机回收无用对象所占内存。
l void runFinalization(): 使java虚拟机调用对象的finalize()释放资源,如文件等
      (2) Example
public static void fullGC(){
Runtime rt = Runtime.getRuntime();
        long isFree = rt.freeMemory();
        long wasFree;
       do{ wasFree = isFree;
           rt.gc();
           isFree = rt.freeMemory();
         }while(isFree > wasFree);
        rt.runFinalization();
}

2.3进程管理
      (1) 创建进程的方法(Runtime)
l Process exec(String command) throws IOException
            各个参数都在字符串command中,用空格隔开。如:
            String cmd = "/bin/ls "+opts+" "+dir;
            Process child = Runtime.getRuntime.exec(cmd);
l public Process exec(String command, String envp[])
envp: 环境数组,格式为name=value, 名中不能有空格
l public Process exec(String cmdarray[])
cmdarray[0]中的字符串是命令名,其他为命令行参数。
l public Process exec(String cmdarray, String envp[])

      新创建的进程称为子进程。反之,创建进程者称为父进程。
      由exec为每个创建的子进程返回一个Process对象。
l 注意:对Process实例的引用赋null值并不能杀死子进程。子进程可以与已存的Java进程同步执行。

      (2) Process的输入输出(Process中)
l public abstract OutputString getOutputString()
返回一个连接到子进程输入的OutputString,写入到这个流的数据子进程作为输入读入。该流是缓冲的。
l public abstract InputString getInputString()
返回一个连接到子进程输出的InputString, 当子进程在输出端写数据时,可从这个流读取数据。该流是缓冲的。
l public abstract InputString getErrorString()
返回一个连接到子进程错误输出的InputString, 当子进程在它的错误输出端写数据时,可从这个流读取数据。该流不是缓冲的, 这样就保证错误能立即报告。
l Example
    public static Process userProg(String cmd) throws IOException {
     Process proc = Runtime.getRuntime().exec(cmd);
       plugTogether(System.in,proc.getOutputString());
       plugTogether(System.out,proc.getInputString()); 
       plugTogether(System.err,proc.getErrorString());
       return proc;
  }

      (3) Process的控制(Process中)
l abstract int waitFor() throws InterruptedException
不确定的等待进程结束,返回它送给System.exit或等价值(通常0成功,非0失败)。若进程已终止,直接返回值。
l public abstract int exitValue()
返回进程退出值。若尚没结束,IllegalStateException。
l public abstract void destroy()
   杀死进程。若进程已完成,则什么也不做。作为废区收集了的Process对象本身并没消亡而仅是不能用于处理。

l Example
    // We have import java.io.* and java.util.*
    public String[] ls(String dir,String opts)
      throws LSFailedException{
       try{   // start up the command
         String[] cmdArray = { "/bin/ls", opts, dir }:
         Process child = Runtime.getRuntime().exec(cmdArray);
         DataInputStream
           in = new DateInputStream(child.getInputStream());
         // read the command's output
         Vector lines = new Vector();
         String line;
         while ((line =in.readLine())!= null)
           lines.addElement(line);
         if (child.waitFor()!=0)   //if the ls failed
          throws new LSFailedException(child.exitValue());
         String[] retval = new String[lines.size()]; 
         lines.copyInfo(retval);
         return retval;
     }catch (LSFailedException e){
         throw e;
     }catch (Exception e) {
        throw new LSFailedException(e.toString());
     }
   }

      (4) void exit(int status) : (Runtime/System中) 终止当前运行的java虚拟机, 状态码0成功完成任务,非0失败。
l Example: 杀死当前组中所有线程,然后调用exit
    public static void safeExit(int status){
     //Get the list of all threads
     Thread myThrd = Thread.currentThread();
     ThreadGroup thisGroup = myThrd.getThreadGroup();
     int count = thisGroup.activeCount();
     Thread[] thrds = new Thread[count+ 20]; 
     thisGroup.enumerate(thrds);
   for (int i = 0; i< thrds.length; i++) {  // stop all threads
         if (thrds[i] != null && thrds[i] != myThrd)
             thrds[i].stop();
   }
   for (int i=0;i<thrds.length;i++){//wait for all threads to complete
        if(thrds[i] != null && thrds[i] != myThrd {
           try {
              thrds[i].join(); //等待线程进入死亡状态
           }catch (InterruptedException e){
              // just skip this thread
          }
        }
    }
     System.exit(status);  // System.exit() calls Runtime.exit()
  }
 
2.4流的本地化
l InputStream getLocalizedInputStream(InputStream in)
l OutputStream getLocalizedOutputStream(OutputStream o)
如键盘产生8位Oriya 字符码,用System.in输入时Oriya 字符被转换成/u0b00至/u0b7f的16位Unicode。本地化的输出流做反向的转换。

2.5杂项
    traceInstructions/traceMethodCalls,布尔型参数为true则打开指令跟踪或方法调用跟踪(打印执行细节),为false则关闭。

3  Math
    Math类由一组静态常数和方法组成,所有运算都以double进行。
    Math.E 代表e,Math.PI代表π。角度用弧度制
        功    能              含    义
        sin(a)                 a的正弦
        cos(a)                 a的余弦
        tan(a)                 a的正切
        asin(v)                v的反正弦,v的范围[-1.0,1.0]
        acos(v)                v的反余弦,v的范围[-1.0,1.0]
        atan(v)                v的反正切,返回的范围[-π/2,π/2]
        atan2(x,y)             x/y的反正切,返回的范围[-π,π]
        exp(x)                 ex
        pow(y,x)            yx
        log(x)                 x的自然对数
        sqrt(x)                x的平方根
        ceil(x)                 大于等于x的最小整数
        floor(x)                小于等于x的最大整数
        rint(x)                 x取整,不舍入
        round(x)             对x四舍五入,即(int)floor(x+0.5)
        abs(x)                 x的绝对值
        max(x,y)              返回x,y的大者
        min(x,y)               返回x,y的小者 
        IEEERemander (x, y) : 按IEEE- 754标准计算余数(取模)。(x/y)*y+x%y == x 若x%y为z,则改变x或y 中的任一个符号仅使z的符号改变。但绝对值是不变的。例如,7%2.5为2.0,-7%2.5为-2.0。
     random(): 返回范围在0.0≤r〈1.0的伪随机数r。
原创粉丝点击