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

} 構造函數

相關文章
相關標籤/搜索