------------------------------------java字节输出流OutputStream概述-----------------------------
字节输入流:InputStream 常用子类 FileInputStream
字节输出流:OutputStream 常用子类 FileOutputStream
字节输出流在写入文本信息的时候是不用释放缓冲区的,字符输出流是要释放缓冲区的数据,使用flush()方法。
OutputStream构造器
FileOutputStream(File file) |
FileOutputStream(File file, boolean append) |
FileOutputStream(FileDescriptor fdObj) |
FileOutputStream(String name) |
FileOutputStream(String name, boolean append) |
写入方法
void | write(byte[] b) |
void | write(byte[] b, int off, int len) |
void | write(int b) |
范例: 使用字节流向文件中写入helloworld
分析:使用三种写入方法
public class OutputStreamDemo {
public static void main(String[] args) {
writeFile();
}
public static void writeFile() {
//创建字节输出流的对象
OutputStream out = null ;
try {
//构造器的演示
//out = new FileOutputStream(newFile("d.txt");
out = new FileOutputStream("d.txt");
//创建可以写入追加数据的构造器
//out = new FileOutputStream("d.txt",true);
//out = new FileOutputStream(newFile("d.txt"),true);
String str = "helloworld";
//把字符串变成字节数组
byte[] bs = str.getBytes();
//单个字节写入方法
for(byte b : bs) {
//需要处理IOexception异常
out.write(b);
}
//写入字节数组方法
out.write(bs);
//写入字节数组的一部分
//第一个是字节数组,第二个是开始索引,第三个是截取的长度
//注意数组越界问题
out.write(bs,8,2);
//最终写入内容helloworldhelloworldld
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(out != null) {
try {
//关闭字节输出流需要处理异常
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}