betacode

Руководство Java SequenceInputStream

  1. SequenceInputStream
  2. Examples

1. SequenceInputStream

SequenceInputStream позволяет объединить (concatenate) два или несколько InputStream вместе. Он считывает от первого byte до последнего byte первого InputStream, затем делает то же самое со следующим InputStream до последнего InputStream.
SequenceInputStream является подкласом InputStream:
SequenceInputStream​ Methods
final void nextStream() throws IOException  

// Methods inherited from InputStream

public int available() throws IOException  
public int read() throws IOException  
public int read(byte b[], int off, int len) throws IOException  
public int read(byte[] b) throws IOException  
public byte[] readAllBytes() throws IOException  
public byte[] readNBytes(int len) throws IOException  
public int readNBytes(byte[] b, int off, int len) throws IOException  

public long skip(long n) throws IOException

public boolean markSupported()
public synchronized void mark(int readlimit)

public synchronized void reset() throws IOException  
public void close() throws IOException

public long transferTo(OutputStream out) throws IOException
Большинство методов SequenceInputStream унаследованы от InputStream, поэтому вы можете узнать, как использовать эти методы в статье о InputStream.
SequenceInputStream​ Constructors
public SequenceInputStream​(InputStream s1, InputStream s2)    

public SequenceInputStream​(Enumeration<? extends InputStream> e)

2. Examples

Предположим, у нас есть два текстовых файла в кодировке UTF-8, каждый файл содержит список названий цветов.
flowers-1.txt
# Flower names (1)

Tulip
Daffodil
Poppy
Sunflower
Bluebell
Rose
Snowdrop
Cherry blossom
flowers-2.txt
# Flower names (2)

Orchid
Iris
Peony
Chrysanthemum
Geranium
Lily
Lotus
Water lily
Dandelion
Hyacinth
Daisy
Crocus
Мы прочитаем вышеуказанные 2 файла с помощью SequenceInputStream, InputStreamReader и BufferedReader.
SequenceInputStreamEx1.java
package org.o7planning.sequenceinputstream.ex;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.SequenceInputStream;

public class SequenceInputStreamEx1 {

    // Windows: C:/Data/test/flowers-1.txt
    private static String file_path1 = "/Volumes/Data/test/flowers-1.txt";
    private static String file_path2 = "/Volumes/Data/test/flowers-2.txt";

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

        InputStream is1 = new FileInputStream(file_path1);
        InputStream is2 = new FileInputStream(file_path2);
        
        // Create SequenceInputStream:
        InputStream is = new SequenceInputStream(is1, is2);
        
        InputStreamReader isr = new InputStreamReader(is, "UTF-8");
        BufferedReader br = new BufferedReader(isr);
        
        String line;
        while((line = br.readLine())!= null)  {
            System.out.println(line);
        }
        br.close();
    }
}
Output:
# Flower names (1)

Tulip
Daffodil
Poppy
Sunflower
Bluebell
Rose
Snowdrop
Cherry blossom
# Flower names (2)

Orchid
Iris
Peony
Chrysanthemum
Geranium
Lily
Lotus
Water lily
Dandelion
Hyacinth
Daisy
Crocus
Улучшим приведенный выше пример, просто распечатаем строку, которая не является пустой и не является строкой комментария (начиная с "#").
SequenceInputStreamEx2.java
package org.o7planning.sequenceinputstream.ex;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.SequenceInputStream;

public class SequenceInputStreamEx2 {

    // Windows: C:/Data/test/flowers-1.txt
    private static String file_path1 = "/Volumes/Data/test/flowers-1.txt";
    private static String file_path2 = "/Volumes/Data/test/flowers-2.txt";

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

        InputStream is1 = new FileInputStream(file_path1);
        InputStream is2 = new FileInputStream(file_path2);
        
        // Create SequenceInputStream:
        InputStream is = new SequenceInputStream(is1, is2);
        
        InputStreamReader isr = new InputStreamReader(is, "UTF-8");
        BufferedReader br = new BufferedReader(isr);
        
        br.lines() // Stream
           .filter(line -> !line.isBlank()) // Not blank
           .filter(line -> !line.startsWith("#")) // Not start with "#"
           .forEach(System.out::println);
        
        br.close();
    }
}
Output:
Tulip
Daffodil
Poppy
Sunflower
Bluebell
Rose
Snowdrop
Cherry blossom
Orchid
Iris
Peony
Chrysanthemum
Geranium
Lily
Lotus
Water lily
Dandelion
Hyacinth
Daisy
Crocus

Руководства Java IO

Show More