FileOutputStream的三种写出方式

package outputstream;

import org.testng.annotations.Test;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 使用FileoutputStream将数据写到文件中,如果文件不存在就创建文件.前提是目录要存在
 */
public class fileoutpustream {
    public static void main(String[] args) {

    }

    @Test
    //单独写一个字符
    public void m1() throws IOException {
        String Path  = "D:\学习\Java学习\IO\Test.txt";
        FileOutputStream fileOutputStream = new FileOutputStream(Path);
        try {
            //注意,如果写入的是一个整数数字,实际存入的是对应ascall码的字符,想要存数字就以字符串的形式存比如:"1"
            fileOutputStream.write(a);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            fileOutputStream.close();
        }
    }
    @Test
    //使用String的getBytes方法
    public void m2() throws IOException {
        String Path  = "D:\学习\Java学习\IO\Test.txt";
        FileOutputStream fileOutputStream = new FileOutputStream(Path);
        try {
            String str = "hello,world~!";
            fileOutputStream.write(str.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            fileOutputStream.close();
        }
     }

     @Test
     //使用FileOutputStream的write(字节数组)的方式
    public void m3() throws IOException {
         String Path  = "D:\学习\Java学习\IO\Test.txt";
         FileOutputStream fileOutputStream = new FileOutputStream(Path);
         try {
             String str = "hello,world~!!";
             fileOutputStream.write(str.getBytes(),0,str.length());
         } catch (IOException e) {
             e.printStackTrace();
         } finally {
             fileOutputStream.close();
         }
     }


    }
经验分享 程序员 微信小程序 职场和发展