目录
3. 应用实例:请使用FileOutputStream 在a.txt 文件中写入”hello,world“,如果文件不存在,会自动创建文件
3.3 第三种方法:使用 write(byte[] b,int off,int len)



- public class FileOutputStream01 {
- public static void main(String[] args) {
-
- }
-
- @Test
- public void writeFile(){
- String filePath = "D:\\a.txt";
- FileOutputStream fileOutputStream = null;
-
- try {
- fileOutputStream = new FileOutputStream(filePath);
- //写入一个字节
- fileOutputStream.write('h');
- fileOutputStream.write('e');
- fileOutputStream.write('l');
- fileOutputStream.write('l');
- fileOutputStream.write('o');
- fileOutputStream.write(',');
- fileOutputStream.write('w');
- fileOutputStream.write('o');
- fileOutputStream.write('r');
- fileOutputStream.write('l');
- fileOutputStream.write('d');
- fileOutputStream.write('!');
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- fileOutputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }


- public class FileOutputStream01 {
- public static void main(String[] args) {
-
- }
-
- @Test
- public void writeFile(){
- String filePath = "D:\\a.txt";
- FileOutputStream fileOutputStream = null;
-
- try {
- fileOutputStream = new FileOutputStream(filePath);
- //写入字符串
- String str = "hello,world!";
- //getBytes():可以将字符串转换成字节数组
- fileOutputStream.write(str.getBytes());
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- fileOutputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }


- public class FileOutputStream01 {
- public static void main(String[] args) {
-
- }
-
- @Test
- public void writeFile(){
- String filePath = "D:\\a.txt";
- FileOutputStream fileOutputStream = null;
-
- try {
- fileOutputStream = new FileOutputStream(filePath);
- //写入一个字符串
- String str = "hello,Jay!";
- fileOutputStream.write(str.getBytes(),0,str.length());
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- fileOutputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }


使用 new FileOutputStream(filePath); 这种创建方式,当写入内容时,会覆盖原先的内容
使用 new FileOutputStream(filePath,true); 这种创建方式,当写入内容时,是追加到文件内容的后面,不会覆盖原先的内容
在程序的执行过程中不会去覆盖本次程序写入到文件的内容。(一个运行流程是不会覆盖的)