import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class TestFIS {
public static void main(String[] args) throws IOException {
// readOne();
// readAll();
readBuf();
}
public static void readOne() throws IOException {
FileInputStream fis = new FileInputStream("d:/a.txt");//a.txt的内容是abc
int read = fis.read();//按字节迭代读取,返回十进制(二进制转换)
System.out.println(read);//97
read = fis.read();//按字节迭代读取,第二个
System.out.println(read);//98
read = fis.read();//按字节迭代读取,第三个
System.out.println(read);//99
read = fis.read();//按字节迭代读取,总共三个字符,超出的返回-1
System.out.println(read);//
}
//循环读取并转换为字符
public static void readAll() throws IOException {
FileInputStream fis = new FileInputStream("d:/a.txt");//a.txt的内容是abc
int read = 0;
while((read=fis.read())!=-1){//()的作用是第一次见,是先进行计算的意思吧
char c = (char) read;//char将int强转,用的就是ascii码表
System.out.println(c);
}
}
//一次读取buf长度个字节
public static void readBuf() throws IOException {
FileInputStream fis = new FileInputStream("d:/a.txt");//a.txt的内容是abc
byte[] buf = new byte[2];
int num = fis.read(buf);//读到的字节数量
String string = new String(buf);//将字符串组转换为字符串
System.out.println(string );
}
}
java FileInputStream
最新推荐文章于 2024-08-01 09:27:12 发布