Java进阶核心之OutputStream流

Java进阶核心之OutputStream流

  • OutputStream是输出字节流的父类,它是一个抽象类
	void write(int b)
	讲解:将指定的字节写入输出流
	
	void write(byte[] b)throws IOException
	讲解:将b.length个字节的byte数组写入当前输出流
	
	void flush() throws IOException
	讲解: write是写到缓冲区中,可以认为是内存中,当缓冲区满时系统会⾃自动将缓冲区的内容写入文件,但是一般还有一部分有可能会留在内存这个缓冲区中, 所以需要调用flush空缓冲区数据。
	
	void close() throws IOException
	讲解:关闭输入流并释放与该流关联的系统资源
  • 常见子类
    • FileOutputStream
      • 抽象类OutputStream用来具体实现类的创建对象, 文件字节输出流, 对文件数据以字节的形式进行行输出的操作
      • 构造函数
	//传入输出的文件地址
	public FileOutputStream(String name)
	
	//传入目标输出的文件对象
	public FileOutputStream(File file)
	
	//传入目标输出的文件对象, 是否可以追加内容
	public FileOutputStream(File file, boolean append)

eg:

package domee.chapter10_3;

import domee.chapter6_6.Vehicle;

import java.io.*;

public class Main {
     
    public static void main(String[] args) throws IOException {
     
        String dir = "C:\\Users\\123\\Desktop\\test";
        String name = "a.txt";
        String name0 = "b.txt";
        File file = new File(dir,name);
        InputStream inputStream = new FileInputStream(file);
//        printlnFile(inputStream);
//        System.out.println("==================");
        OutputStream outputStream = new FileOutputStream(dir+File.separator+name0);
        //testWrite(inputStream,outputStream);
        testWriteBuf(inputStream,outputStream);

    }

    public static void read(InputStream inputStream)throws IOException{
     
        int readrulst =  inputStream.read();
        System.out.println(readrulst);
    }

    public static void printlnFile(InputStream inputStream)throws IOException{
     
        byte[] buf = new byte[inputStream.available()];
        int lenget;
        while ((lenget = inputStream.read(buf)) != -1){
     
            System.out.print(new String(buf,0,lenget));
        }
        inputStream.close();


    }
    //单个字节读取性能差效果不好,中文会有乱码
    public static void testWrite(InputStream inputStream,OutputStream outputStream)throws IOException{
     
        int value = 0;
        while (value != -1){
     
            value = inputStream.read();
            //System.out.print(value);
            outputStream.write(value);
        }
        inputStream.close();
        outputStream.close();
    }

    public static void testWriteBuf(InputStream inputStream,OutputStream outputStream)throws IOException{
     
        byte[] buf = new byte[1024];
        int length;
        while ((length = inputStream.read(buf)) != -1){
     
            outputStream.write(buf,0,length);
        }
        inputStream.close();
        outputStream.close();
    }

}

在这里插入图片描述
Java进阶核心之OutputStream流_第1张图片

你可能感兴趣的:(Java,SE,java)