InputStream:输入流,将文件从硬盘读取到内存
OutputStream:输出流,将文件从内存写入到硬盘
第一种读取方式:自己指定固定的字节数组,一批一批地进行读取
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class Test5 {
public static void main(String[] args) throws Exception {
File file=new File("D:/a.txt");
InputStream inputStream=new FileInputStream(file);
byte []b=new byte[1024];
int len=inputStream.read(b);
inputStream.close();
System.out.println("内容:"+new String(b,0,len));
}
}
运行结果:
文件内容:
第二种读取方式:先获取文件内容的长度,然后指定对应文件长度的字节数组进行读取
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class Test5 {
public static void main(String[] args) throws Exception {
File file=new File("D:/a.txt");
InputStream inputStream=new FileInputStream(file);
int len=(int) file.length();
byte []b=new byte[len];
inputStream.read(b);
inputStream.close();
System.out.println("内容:"+new String(b));
}
}
运行结果:
文件内容:
第三种读取方式:一个字节一个字节地读取
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class Test5 {
public static void main(String[] args) throws Exception {
File file=new File("D:/a.txt");
InputStream inputStream=new FileInputStream(file);
int fileLength=(int) file.length();
byte []b=new byte[fileLength];
int temp=0;
int len=0;
while((temp=inputStream.read())!=-1) {
b[len++]=(byte) temp; //一个字节一个字节地读取,放到b字节数组里面
}
inputStream.close();
System.out.println("内容:"+new String(b));
}
}
结果: