FileInputStream:通过字节的方式读取文件。
FileOutputStream:通过字节的方式写出或追加数据到文件。
public class IOTest03 {
public static void main(String[] args) {
InputStream is=null;
File file=new File("a.txt");//数据源
try {
is=new FileInputStream(file);//选择流
int len=-1;
byte[] bytes=new byte[5];//五个一组,进行读取
while((len=is.read(bytes))!=-1){//循环读取内容
String string=new String(bytes,0,len);//字节数组-->字符串
System.out.println(string);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(is!=null){//如果is读取到了内容,证明流打开了需要关闭
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class IOTest04 {
public static void main(String[] args) {
File file=new File("b.txt");//创建源
OutputStream os=null;
try {
//选择流,true表明每次执行,原来的语句不覆盖
os=new FileOutputStream(file,true);
String str="Hello World!\r\n";//换行
byte[] bytes=str.getBytes();//字符串-->字节数组
os.write(bytes,0,bytes.length);//将bytes数组的内容输入
os.flush();//刷新缓冲
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if(os!=null){
os.close();//关闭流
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}