大家好,又见面了,我是你们的朋友全栈君。
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class InputStreamDemo {
/*
* InputStream字节输入流
* FileInputStream:文件字节输入流
* --->构造方法
* 1.new FileInputStream(File file):
* 传入File对象,代表了文件源
* 2.new FileInputStream(String name):
* 传入String类型的文件路径,该路径代表的文件是文件源。
*/
public static void main(String[] args) {
File file = new File("D:/test/a.txt");
InputStream is = null;
try {
is= new FileInputStream(file);
/*
* int|read():一次一个字节,返回int Unicode编码表
*/
/*int i = is.read();
System.out.println(i);
*/
/*
* int | read(byte[] bytes):把读取到的内容存入byte数组中,
* 返回值为每次读取到的字节的个数。如果不存在则返回-1
*/
/* String str = "";
int len = 0;
byte[] bytes = new byte[3];
while((len = is.read(bytes)) != -1){//还有剩余内容
//System.out.println(Arrays.toString(bytes));
String s = new String(bytes,0,len);
str += s;
}
System.out.println(str);
*/
/*
* int | read(byte[] bytes , int off,int len):
* 把读取到的内容存入bytes数组中,每次从下标为off开始
* 最多存储len个,返回值为每次读取到的字节的个数。
* 如果读取不到内容则返回-1
*/
byte[] bytes = new byte[3];
String str = "";
int len = 0;
while((len = is.read(bytes, 1, 2)) != -1){
String s = new String(bytes,1,len);
str += s;
}
System.out.println(str);
} catch (IOException e) {
e.printStackTrace();
}finally{
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/191044.html原文链接:https://javaforall.cn