大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。
Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺
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.net/191044.html原文链接:https://javaforall.net
