使用输出流一般要四个步骤
1.给出输出流目的地
2.创建指向目的地的输出流
3.让输出流把数据写入到目的地
4.关闭输出流
1.首先是构造方法创建输出目的地,
FileOutputStream out = new FileOutputStream ("文件名");
或:File f = new File (“文件名”);
FileOutputStream out = new FileOutputStream (f);
2.使用输出流写入字节
用继承的write方法去写入字节
void write(int n) | 向目的地写入单个字节 |
void write (byte b[ ]) | 向目的地写入字节数组 |
void write (byte b[ ],int off,int len) | 向目的地写入字节数组从偏移量off开始取len个字节 |
3.关闭流
用close()方法
import java.io.*;
public class wenjian_outputStream {
@SuppressWarnings("resource")
public static void main(String[] args) throws IOException {
File f = new File("hello.txt");
byte [] a = "王者七连败".getBytes("utf-8");//获取字节并转码
byte [] b = "小丑竟是我自己".getBytes("utf-8");
// TODO Auto-generated method stub
FileOutputStream out = new FileOutputStream("hello.txt");//可以创建文件也可以指定文件
out.write(a,0,a.length);//out.write(a)两种方法都可
System.out.println(f.length());
out = new FileOutputStream("hello.txt",true);//向文件尾加内容,第二个属性为boolean值,为true会从文件末尾开始写入数据,false则会刷新文件,把之前的覆盖掉
out.write(b);
System.out.println(f.length());
}
}