FileInputStream字节输入流

    科技2022-07-12  128

    import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; /*FileInputStream读取文件内容 D:/abc.txt文件内容:ABCabcjbpower*/ public class Test9 { public static void main(String[] args) throws IOException { m1(); System.out.println(); m2(); System.out.println(); m3(); } private static void m3() throws IOException { FileInputStream fis=new FileInputStream("D:/abc.txt"); byte bytes[]=new byte[4]; int len=fis.read(bytes); System.out.println(len);//长度 while(len!=-1){ //String类中的构造方法new String(数组名,起始下标,数组长度)方法 System.out.print(new String(bytes,0,len)); len=fis.read(bytes); } fis.close(); } private static void m2() throws IOException { FileInputStream fis=new FileInputStream("D:/abc.txt"); byte bytes[]=new byte[4]; fis.read(bytes);//文件读取4个字节 System.out.println(Arrays.toString(bytes));//[65, 66, 67, 97] //注释:文件为什么打印的不是ABCa?解:数组只能存放数字 } private static void m1() throws IOException { //读取D:/abc.txt文件内容,通过构造方法指定要访问的文件,,如果文件不存在就会抛出异常 FileInputStream fis=new FileInputStream("D:/abc.txt"); //在FileInputStream类中调用read()方法从文件中读取一个字节,在文件末尾返回-1 int cc=fis.read();//每次只能读取一个字节 while(cc!=-1){ System.out.print((char)cc);//int类型强转char类 cc=fis.read(); } fis.close(); } }

    FileInputStream在控制台中显示如下:

     

    Processed: 0.011, SQL: 8