/**
*<li> InputStream类中定义的方法:
* <li>读取的数据保存在字节数组中,返回读取的字节数组的长度:public int read(byte[] b) throws IOException ;
* <li>读取部分数据保存在字节数组中,返回读取数据的长度:public int read(byte[] b,int off,int len)throws IOException ;
* 如果文件内容读取到结尾字返回-1;
*/
package com.java.demo;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class TestDemo {
public static void main(String args[]) throws Exception{
//设置文件路径
File fl = new File("e:"+File.separator+"hello" + File.separator+"demo" +File.separator+"java.txt" );
if(fl.exists()){ //文件存在
InputStream in = new FileInputStream(fl) ;
byte data[] = new byte[1];
int len = in.read(data) ;//将读取的内容保存在字节数组中,并且返回字节长度
System.out.println("【"+new String(data,0,len) +"】");
} }
}
重要的实现方式:public abstract int read() throws IOException ;
/**
*<li>读取单个字节,如果读取到最后则返回-1: public abstract int read()throws IOException ;
*/
package com.java.demo;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class TestDemo {
public static void main(String args[]) throws Exception{
//设置文件路径
File fl = new File("e:"+File.separator+"hello" + File.separator+"demo" +File.separator+"java.txt" );
if(fl.exists()){ //文件存在
InputStream in = new FileInputStream(fl) ;
byte data[] = new byte[1024];
int foot = 0 ;
int temp = 0 ;
while((temp = in.read()) != -1){ //说明存在数据
data[foot ++] = (byte)temp;//将读取的数据保存在字节数组中
}
in.close();
System.out.println("[" + new String(data,0,foot)+"]");
} }
}