FileOutputStream应用实例
- 该类用来创建一个文件并向文件中写数据。
- 如果该流在打开文件进行输出前,目标文件不存在,那么该流会创建该文件。
- 有两个构造方法可以用来创建 FileOutputStream 对象。
- 使用字符串类型的文件名来创建一个输出流对象:
法一: OutputStreamf = newFileOutputStream(“C:/java/hello”) 法二: Filef = newFile(“C:/java/hello”); OutputStreamfOut = newFileOutputStream(f);
要求:
请使用FileOutputStream在a.txt文件,中写入“hello, world”,如果文件不存在,会创建文件
(注意:前提是目录已经存在.)
package test;import org.junit.Test;import java.io.FileOutputStream;import java.io.IOException;/*** 演示FileOutputStream的使用(字节输入流程序 --> 文件)*/public class Main {public static void main(String[] args) {Main main = new Main();main.writeFile();}/*** 演示使用FileOutputStream 将数据写到文件中,* 如果该文件不存在,则创建该文件*/@Testpublic void writeFile() {//创建 FileOutputStream对象String filePath = "D:\\a.txt";FileOutputStream fileOutputStream = null;try {//得到 FileOutputStream对象 对象//1. new FileOutputStream(filePath) 创建方式,当写入内容是,会覆盖原来的内容//2. new FileOutputStream(filePath, true) 创建方式,当写入内容是,是追加到文件后面//覆盖内容写法fileOutputStream = new FileOutputStream(filePath);//追加内容写法//fileOutputStream = new FileOutputStream(filePath, true);//写入一个字节//fileOutputStream.write('H');////写入字符串String str = "hello world!";//str.getBytes() 可以把 字符串-> 字节数组//fileOutputStream.write(str.getBytes());//内容全部写入//等价于//fileOutputStream.write(str.getBytes(),0,str.length());/*write(byte[] b, int off, int len) 将 len字节从位于偏移量 off的指定字节数组写入此文件输出流*/fileOutputStream.write(str.getBytes(), 0, 3);//截取写入} catch (IOException e) {e.printStackTrace();} finally {try {fileOutputStream.close();} catch (IOException e) {e.printStackTrace();}}}}

