文章目录
前言
IO流---FileInputStream文件字节输入流和FileOutputStream文件字节输出流字节流可以读写任何类型的文件:纯文本文件、视频、音频、图片等一、FileInputStream 文件字节输入流
1.FIleInputStream类中方法:
int read():返回文件中读取到的字节"本身"。
int read(byte[] bytes):返回文件中读取到的字节数量。
* 若已经读取完成,这两种方法都返回 -1 。
int available():返回流中未读取的字节数量。
long skip(long n):跳过n个字节读取。
2.FIleInputStream读取文件实例:
代码如下:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileInputStreamIoWin {
public static void main(String[] ages){
//创建文件字节输入流
FileInputStream fis=null;
try {
//赋予流读取文件的位置和名称
fis = new FileInputStream("copytxt");
//开始读文件
// byte[] bytes = new byte[4];
// int readCount = 0;
// while(true){
// if ((readCount=fis.read(bytes)) == -1){
// break;
// }
// System.out.print(new String(bytes,0,readCount));
// }
byte[] bytes = new byte[4];
int readCount = 0;//返回的读取到的字节数量
while((readCount=fis.read(bytes)) != -1){//若读取到的字节数量不为-1,表示文件未完全读取完
System.out.print(new String(bytes,0,readCount));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
二、FileOutputStream 文件字节输出流
1.FIleOutputStream类中方法:
构造方法:以追加的方式在文件末尾写入,不清空原文件内容append=true
FileOutputStream("地址",boolean append){
}
void write(byte[] bytes):将byte数组中的字节全部写到硬盘中。
void write(byte[] bytes,写起始位置,写长度):将byte数组中的字节从写起始位置开始写,写写长度个字节。
三、文件复制(实例)
代码如下:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/***
* 文件复制:F盘——>D盘
*/
public class FileCopyIO {
public static void main(String[] args) {
//创建输入流和输出流
FileInputStream fis = null;
FileOutputStream fos = null;
try {
//原文件地址
fis = new FileInputStream("F:/IOText/FileInputStreamsx");
//目标文件地址
fos = new FileOutputStream("D:\\CopyFIle");
//可是读文件,边读边写
byte[] bytes = new byte[1024*1024];
//返回读取到的字节数量
int readCount;
while((readCount = fis.read(bytes)) != -1){
fos.write(bytes,0,readCount);
}
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
总结
IO流中FileReader和FileWriter与FileInputStream和FileOutputStream有异曲同工之妙,下一章,我们来了解FileReader和FileWriter。