java Io

来源:互联网 发布:hm淘宝上代购是正品吗 编辑:程序博客网 时间:2024/05/01 14:47
1 、循环方式计算阶乘,又叫迭代。
public int compute(int number){
int result = 1;
for(int i = number; i > 0;i--){
result *= i;
}
return result;
}


2 使用递归方法计算阶乘 ,所谓递归就是方法调用自身。对于递归来说,一定有一个出口,让递归结束,只有这样才能保证不出现死循环。
public int compute2 (int number){
if(1 == number){
return 1;
}else{
return number * compute2(number -1);
}
}
3、斐波那契数列 1 、1、 2、3、5、8、13、21、...................
//使用递归计算斐波那契数列
public int compute(int n){
//递归的出口
if(1 == n || 2 == n){
return 1;
}else{
return compute(n -1) + compute(n-2);
}

}
4、字节流的输入流和输出流的基础是InputStream 和OutputStream;字符流的输入流和输出流的基础是Reader和Writer

 字符流也是基于字节流的。


字符流也是基于字节流的。

 

5 、输入流

读数据的逻辑:

open a stream

while more information

read information

close the stream

6 、节点流:从特定地方读写的流,例如:磁盘或者内存。

过滤流:使用节点流作为输入和输出。

7、 三个基本方法

 abstract    int     read(); 读取一个字节数据,并返回读到的数据,如果返回 -1  ,表示读到了输入流的末尾。

int     read(byte[          ] b);将输入读入一个字节数组,同时返回实际读取的字节数。如果返回 -1, 表示读到了输入流的末尾。

int      read(byte[  ] b,int off,int len);将数据读入一个字节数组,同时返回实际读取的字节数。如果返回  -1 ,表示读到了输入流的末尾。off指定数组b中存放数据的起始偏移位置;len指定读取的最大字节数。

为什么只有第一个read方法是抽象的?答:因为第二个read方法依靠第三个read ,而第三个read依靠第一个read实现。

 

读取流的例子:

    InputStream is = new FileInputStream("c:/hello.txt");

       byte[] buffer =new byte[200];

      

       int length = 0;

      

       //每次最多读200个字节,但不一定够200个,当读到末尾的时候,返回   -1

       while(-1 != (length = is.read(buffer,0,200))){

           String str = new String(buffer,0,length);//把字符数组(从数组的0length)转换为字符串

           System.out.println(str);

       }

       is.close();



 
原创粉丝点击