JAVA IO - InputStream

InputStream从源读取数据放入到byte数组中,当读到文件末尾时返回-1. java

另外就是从byte数组转成String,String自己提供可构造函数。 数组

固然InputStream自己要提供了无参的read方法逐个byte读出。 函数

InputStream和OutputStream都须要关闭,因此将其close方法放在finally块中是比较好的方法 code

import java.io.FileInputStream; import java.io.InputStream; io

public class ReadByteFromFile { class

 /**   * @param args   */  public static void main(String[] args) throws Exception {   // TODO Auto-generated method stub         InputStream in = new FileInputStream("helloWorld.txt");         byte[] bs= new byte[1024];         int b = -1;         int start = 0;         while(( b = in.read()) != -1){          bs[start] = (byte)b;          start++;         }                 System.out.println(new String(bs, 0, start));         in.close();  } import

} 构造函数

相关文章
相关标签/搜索