Java InputStream

InputStream Java I/O java.io

InputStream

InputStream FileInputStreamByteArrayInputStream


InputStream Java IO 8

InputStream

""

java-inputstream.png [java-inputstream.png]

int read() 0~255 int -1
int read(byte[] b) b.length b
int read(byte[] b, int off, int len) off len b
void close()

public abstract int read() throws IOException

InputStream 0 255 int -1

InputStream input = new FileInputStream("example.txt");
int data = input.read();
while(data != -1) {
    System.out.print((char)data);
    data = input.read();
}
input.close();

public int read(byte[] b) throws IOException

b.length -1

InputStream input = new FileInputStream("example.txt");
byte[] buffer = new byte[1024];
int bytesRead;
while((bytesRead = input.read(buffer)) != -1) {
    System.out.println("Read " + bytesRead + " bytes");
}
input.close();

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

(off)(len)

InputStream input = new FileInputStream("example.txt");
byte[] buffer = new byte[1024];
int bytesRead = input.read(buffer, 10, 500); // buffer[10]500
input.close();

public long skip(long n) throws IOException

n

public int available() throws IOException

2.6

public void close() throws IOException


  • FileInputStream:
  • ByteArrayInputStream:
  • FilterInputStream:
  • ObjectInputStream: ObjectOutputStream
  • PipedInputStream: PipedOutputStream

try-with-resources

Java 7 try-with-resources AutoCloseable

try (InputStream input = new FileInputStream("example.txt")) {
    int data;
    while ((data = input.read()) != -1) {
        System.out.print((char)data);
    }
} catch (IOException e) {
    e.printStackTrace();
}

BufferedInputStream

try (InputStream input = new BufferedInputStream(new FileInputStream("largefile.dat"))) {
    //
} catch (IOException e) {
    e.printStackTrace();
}

IO IOException


5.

read() int byte

(-1) byte -1

InputStream String

public static String convertToString(InputStream input) throws IOException {
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(input))) {
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
        }
        return stringBuilder.toString();
    }
}

InputStream

InputStream ByteArrayInputStream


6.

InputStream Java I/O InputStream