IO streams - input and output streams of bytes to copy, file

I 流


  • I: input - an input (read), eg: to read the contents of the hard disk memory
  • O: output - output (write) eg: put things in memory is written to disk to save
  • Flow: numeric (text / byte) characters generally 1 = 2Byte, 1Byte = 8bit

Byte stream to read arbitrary files: Music / Pictures / ...,

  • Throws an exception file does not exist, unified here throws throw JVm process can also try catch

Output stream of bytes - the parent of all bytes output


  • java.io.OutputStream - output stream of bytes top abstract parent class, are the following abstract methods

    1. void close ()
      Closes this output stream and releases any system resources associated with this stream.

    2. void flush ()
      Flushes this output stream and forces any buffered output bytes to be written.

    3. void write (byte [] b)
      The b.length bytes written to this output stream from the specified byte array.

    4. void write (byte [] b, int off, int len)
      specified byte array starting at offset off len bytes written to this output stream.

    5. abstract void write (int b)
      the specified byte to this output stream.

java.io.FileOutpuStream extends OutputStream


  • FileOutputStream: file byte output stream
    1. Role: the memory of things to write files

    2. Construction method:

      FileOutputStream (String name)
      Creates a write data to a file with the specified name of the output file stream.

    FileOutputStream (File file)
    to create a file for writing data file represented by the specified File object in the output stream.

    1. FileOutputStream (File File, boolean the append)
      the append switch to append written, true to the additional write, false to create a new file

    2. The role of the constructor:
      1. Create a FileOutputStream object
      2. Based on the file transfer constructor / file path, creating an empty file
      3. FileOutputStream object will point to create a good document
  • Data written to the principle (memory -> hard drive)
    1. java program - JVM virtual machine - OS - OS calls the method of writing data - written documents
  • Step output stream of bytes used
    1. Creating FileOUtputStream object and write data transfer destination
    2. FileOutputStream object method call, write method to write files
    3. , The flow will take up memory to free up resources
import java.io.FileOutputStream;
import java.io.IOException;
public class IOApi {
    public static void main(String[] args) throws IOException {

        //构造方法中绑定要写入数据的目的地
        FileOutputStream output = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\java_code\\test.txt");

        output.write(65);   //十进制65 -> 二进制100 0001‬
        /*
        任意的文本编辑器,在打开文件时都会查询编码表,把字节表示转换
        字符表示

        若是0-127,则会查询ASCII表
        其他值:查询系统默认表(中文系统查询JDK编码表)
        即:上文写入A

        */

        //一次写多个字节

        output.close();
    }
}

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

public class IOApi {
    public static void main(String[] args) throws IOException {

        //使用File生成写入数据目的地,相对路径(不使用File也可以)
        FileOutputStream output = new FileOutputStream(new File("b.txt"));

        output.write(49);  //写入三个字节显示为1
        output.write(48);  //写入三个字节显示为0
        output.write(48);  //写入三个字节显示为0

        output.close();
    }
}
  • Continuous writing multiple bytes, the above optimization

    1. If you write the first byte is a positive integer (0-127), then queries the ASCII code table display
    2. If you wrote the first one is negative, then the first byte and the second byte will display text
      characters, the query is the default code table (GBK)
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class IOApi {
    public static void main(String[] args) throws IOException {

        //使用File生成写入数据目的地,相对路径(不使用File也可以)
        FileOutputStream output = new FileOutputStream(new File("b.txt"));

        byte[] bytes ={49,48,48};

        output.write(bytes);  //100

        byte[] bytes1 ={-56,78,48};
        output.write(bytes1);  //100萅0

        //public void write(byte[],int off,int len) :把字节数组的一部分写入到文件中
        //从偏移量off开始输出到此输出流,从指定的字节数组写入len字节

        output.write(bytes,1,2);  //100萅000

        //String,出现乱码,可能是上面字节与下面字符转换的字节配对
        //写在第一行没问题
        output.write("你好呀".getBytes());  //00萅000浣犲ソ鍛€
        
        output.close();
    }
}
  • Additional data and linefeed
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class IOApi {
    public static void main(String[] args) throws IOException {

        //打开追加写开关,false创建新文件,覆盖源文件。
        FileOutputStream output = new FileOutputStream("b.txt",true);

        //String
        output.write("你好呀".getBytes());

        //Windows: \r\n
        //Linux:/n
        //Mac:/r
        output.write("\n好呀".getBytes());

        output.close();
    }
}

Input stream of bytes - the superclass of all input byte


  • The method java.io.InputStream extends Object common portion of all subclasses:

    1. abstract int read ()
      Reads the next byte of data from the input stream.
    2. int read (byte [] b)
      reads a certain number of bytes from the input stream, and stores it in the buffer array b.
    3. int read (byte [] b, int off, int len)
      the input stream up to len bytes of data is read into the byte array.

    4. void close ()
      Closes this input stream and releases any system resources associated with the stream.

java.io.FileInputStream extends InputStream


  • Role: The hard disk file read into memory

  • Construction method:

    1. FileInputStream (File File)
      File: Data Source
    2. FileInputStream (FileDescriptor fdObj)
      Creates a FileInputStream by using the file descriptor fdObj, which represents a connection to an existing file system to an actual file.
    3. FileInputStream (String name)
      name: File Path
    • The role of the constructor:

      1. It creates a FileInputSteam objects
      2. FileInputStream constructor will file specified in the object to be read
  • Read data Principle: java program - JVM - OS - OS calls the method of reading data - to read the file

  • Step input stream of bytes
    1. Create a FileInputStream object constructor to bind the data source to read
    2. The method using FileInputStream read, read the file
    3. Release resources
import java.io.FileInputStream;
import java.io.IOException;

public class IOApi {
   public static void main(String[] args) throws IOException {

       //相对路径获取数据源
       FileInputStream input = new FileInputStream("b.txt");

       //使用read方法读取,一次读取一个字节,会返回一个Int值
       System.out.println(input.read());  //239 你
       //读取的第二个值
       System.out.println(input.read());  //187 好

       //当input.read返回 -1 时代表读取结束,说明读取到了结束标记
       while(input.read() != -1){
           System.out.println(input.read());
       } 
       

       //关闭输入数据流,释放资源
       input.close();
   }
} 
  • Input stream of bytes read by a number of bytes

int read (byte [] b) a number of bytes read from the input stream, and stores it in the buffer
array b.

byte [] b: cushion, generally defined as a length of 1024 (1kB) or an integral multiple of 1024
int: a valid return value is the number of bytes

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;

public class IOApi {
   public static void main(String[] args) throws IOException {

       //相对路径获取数据源
       FileInputStream input = new FileInputStream("b.txt");

       //连续读,给定一个字节数组,中文字符如果设置的数组不足够长,会有乱码
       //byte[] inp = new byte[10];出现中文乱码,读取不完全
       //数组作用:起到缓冲作用
       byte[] inp = new byte[20];
       
       //read(byte[] b)从输入流中读取一定数量的字节,并将其存储在缓冲区数组 b 中,字节数组 b 实际是一个不断重复覆盖的过程
       //input.read(inp)返回的是读取的有效字节的个数
       System.out.println(input.read(inp));  //19
       
       //使用数组工具类转换为码值
       //当数组长度为10时 [-17, -69, -65, -28, -67, -96, -27, -91, -67, -27]
       //当数组长度为20时 [-17, -69, -65, -28, -67, -96, -27, -91, -67, -27, -111, -128, 10, -27, -91, -67, -27, -111, -128, 0]
       System.out.println(Arrays.toString(inp));

       /*
       String类的构造方法转换
       String[byte[] bytes] : 把字节数组转换为字符串
       String(byte[] bytes,int offset,int length)把字符数组的一部分转换为字符串,
       offset:偏移位置,length:转换个数
        */
       
       //出现乱码,是因为给的byte[10]长度不够,换为byte[20]正常
       //长度为10 你好� ;长度为20 显示正常
       System.out.println(new String(inp));

       /*********************************************
       为什么要用偏移量0,因为如果数组过大,容易浪费空间
       所以可以设置长度为input.read(inp)的返回值,也就是19,如下
       System.out.println(new String(inp,0,19));
       *********************************************/

       //关闭输入数据流,释放资源
       input.close();
   }
}

File Copy


  • Principle: a read, a write, any byte stream files can be copied
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;

public class IOApi {
    public static void main(String[] args) throws IOException {

        //读,相对路径获取数据源
        FileInputStream input = new FileInputStream("b.txt");
        byte[] inp = new byte[1024];
        //len为读取的有效字节位数
        int len = input.read(inp);

        //写,相对路径给出文件写入抽象位置
        FileOutputStream output = new FileOutputStream("b_copy.txt");
        //给出写入数据,从0开始到有效位置结束
        output.write(inp,0,len);

        

        //优化代码
        FileInputStream inputJpg = new FileInputStream("C:\\Users\\Administrator\\Pictures\\1.jpg");
        FileOutputStream outputJpg = new FileOutputStream("C:\\Users\\Administrator\\Pictures\\1_copy.jpg");
        //注,中文结束位会报错,陷入死循环,可复制图片,图片大,用字节数组处理快
        byte[] bytes= new byte[1024*1024];
        int lenJpg = 0;
        while((lenJpg = inputJpg.read(bytes)) != -1){
            outputJpg.write(bytes,0,lenJpg);
        }

        //先释放写的,写完一定读完了
        outputJpg.close();
        inputJpg.close();
    }
}

Guess you like

Origin www.cnblogs.com/huxiaobai/p/11575442.html