FileInputStream类和FileOutputStream类的学习
JAVA IO流中主要可以分为字节流和字符流。FileInputStream类和FileOutputStream类它们分别是InputStream抽象类和 OutputStream抽象类的实现子类,都属于字节流。
1,FileInputStream简单使用
该类通过字节的方式读取文件,适合读取所有类型的文件(图像、视频)
test.txt的内容为
hello IO
Test01.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class Test01 {
public static void main(String[] args) {
//创建源
File src=new File("test.txt");
// System.out.println(System.getProperty("user.dir"));
//选择流
InputStream is=null;
try {
is=new FileInputStream(src);
//分段读取操作(也可以采用按字节一个一个的读取操作)
byte[] flush=new byte[10];//缓冲容器,一次性能接收10个字节
int len;//接收长度
while((len=is.read(flush))!=-1) {
//字节数组--》字符串(解码)
String str=new String(flush,0,len);
System.out.println(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
//释放资源
try {
if(is!=null) {
is.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
文件中的内容可以成功读出。
2,FileOutputStream简单使用
该类可以通过字节的方式写出或追加数据到文件,适合所有类型的文件。
Test02.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class Test02{
public static void main(String[] args) {
//创建源
File src=new File("dest.txt");//目标文件不存在,会自动地创建。
//选择流
OutputStream os=null;
try {
os=new FileOutputStream(src,true);//选择要输出的目标文件路径,并允许内容可追加
//进行写操作
String msg="I am studying IO";
byte[] datas=msg.getBytes();//进行编码
os.write(datas, 0, datas.length);//写出操作
os.flush();//避免数据滞留在内存中,进行刷新
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(os!=null) {
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
可以看出内容成功的写入到相应的文件中。