Open file in inputstream java

Java InputStream

Java InputStream tutorial shows how to work with InputStream class in Java.

is a flow of data from a source or into a destination. A good metaphor for Java streams is water flowing from a tap into a bathtub and later into a drainage. InputStream and OutputStream are abstractions over low-level access to data, such as C file pointers.

Java InputStream

InputStream is a source for reading data. A stream can represent various kinds of sources, including disk files, devices, other programs, and memory arrays.

Streams support many different types of data, including simple bytes, primitive data types, localized characters, and objects.

Java InputStream subclasses

InputStream is an abstract class; it is a superclass for all classes representing an input stream of bytes, including AudioInputStream , ByteArrayInputStream , FileInputStream , FilterInputStream , ObjectInputStream , PipedInputStream , and SequenceInputStream .

Java InputStream close

The FileInputStream’s close method closes the input stream and releases any system resources associated with this stream. In our examples we use try-with-resources statement, which ensures that each resource is closed at the end of the statement.

Java InputStream read

  • read(byte[] b) — reads up to b.length bytes of data from this input stream into an array of bytes.
  • read(byte[] b, int off, int len) — reads up to len bytes of data from this input stream into an array of bytes.
  • read — reads one byte from the file input stream.
Читайте также:  Edu ru modules php

Java InputStream read text

The following example shows how to read a text file with InputStream .

The Battle of Thermopylae was fought between an alliance of Greek city-states, led by King Leonidas of Sparta, and the Persian Empire of Xerxes I over the course of three days, during the second Persian invasion of Greece.

In the example, we use this text file.

package com.zetcode; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; public class JavaInputStreamText < public static void main(String[] args) throws IOException < String fileName = "src/resources/thermopylae.txt"; try (InputStream fis = new FileInputStream(fileName); InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8); BufferedReader br = new BufferedReader(isr)) < br.lines().forEach(line ->System.out.println(line)); > > >

The text file is read with FileInputStream , InputStreamReader , and BufferedReader .

try (InputStream fis = new FileInputStream(fileName);

FileInputStream is a specialization of the InputStream for reading bytes from a file.

InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);

InputStreamReader is a bridge from byte streams to character streams: it reads bytes and decodes them into characters using a specified charset.

BufferedReader br = new BufferedReader(isr)) 

BufferedReader reads text from a character-input stream, buffering characters for efficient reading of characters, arrays, and lines.

br.lines().forEach(line -> System.out.println(line));

The data is read by lines from a buffered reader.

Java InputStream read bytes

The read methods of InputStream read bytes.

package com.zetcode; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; public class JavaInputStreamBytes < public static void main(String[] args) throws IOException < String fileName = "src/resources/ball.png"; try (InputStream is = new FileInputStream(fileName)) < byte[] buffer = new byte[is.available()]; is.read(buffer); int i = 0; for (byte b: buffer) < if (i % 10 == 0) < System.out.println(); >System.out.printf("%02x ", b); i++; > > System.out.println(); > >

The example reads bytes from a PNG image and prints the bytes in hexadecimal format to the console.

try (InputStream is = new FileInputStream(fileName)) 

We use FileInputStream to read bytes from an image file.

byte[] buffer = new byte[is.available()]; is.read(buffer);

With the read method, we read the bytes into the array of bytes.

int i = 0; for (byte b: buffer) < if (i % 10 == 0) < System.out.println(); >System.out.printf("%02x ", b); i++; >

We go through the array and print the bytes to the console in hexadecimal format.

89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 00 0a 00 00 00 0a 08 06 00 00 00 8d 32 cf bd 00 00 00 04 73 42 49 54 08 08 08 08 7c 08 64 88 00 00 00 09 70 48 59 73 00 00 0d d7 00 00 0d d7 01 42 28 9b 78 00 00 00 19 74 45 58 74 53 6f .

This is a partial sample output of the example.

Java InputStream read from URL

InputStream allows to read data from a URL source.

package com.zetcode; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; public class JavaInputStreamURL < public static void main(String[] args) throws IOException < String webSite = "http://www.something.com"; URL url = new URL(webSite); try (InputStream is = url.openStream(); BufferedReader br = new BufferedReader( new InputStreamReader(is))) < br.lines().forEach(System.out::println); >> >

The example opens an InputStream to a web page and reads its data.

try (InputStream is = url.openStream();

An InputStream to a URL is created with openStream method.

Java InputStream read deserialized data

ObjectInputStream reads serialized data previously written using ObjectOutputStream .

package com.zetcode; import java.io.Serializable; public class Country implements Serializable < static final long serialVersionUID = 42L; private String name; private int population; public Country(String name, int population) < this.name = name; this.population = population; >public String getName() < return name; >public void setName(String name) < this.name = name; >public int getPopulation() < return population; >public void setPopulation(int population) < this.population = population; >>

This is the Country bean. We are going to serialize and deserialize a list of countries.

package com.zetcode; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; public class JavaObjectOutputStreamEx < public static void main(String[] args) throws IOException < String fileName = "src/resources/myfile.dat"; try (OutputStream fis = new FileOutputStream(fileName); ObjectOutputStream out = new ObjectOutputStream(fis)) < Listcountries = new ArrayList<>(); countries.add(new Country("Slovakia", 5429000)); countries.add(new Country("Norway", 5271000)); countries.add(new Country("Croatia", 4225000)); countries.add(new Country("Russia", 143439000)); out.writeObject(countries); > > >

The example serializes a list of objects.

A list of countries is written to the ObjectOutputStream .

package com.zetcode; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.util.List; public class JavaInputStreamObjects < public static void main(String[] args) throws IOException, ClassNotFoundException < String fileName = "src/resources/myfile.dat"; try (InputStream fis = new FileInputStream(fileName); ObjectInputStream oin = new ObjectInputStream(fis)) < Listcountries = (List) oin.readObject(); countries.forEach(System.out::println); > > >

We use the ObjectInputStream to read serialized data.

Java InputStream read sequence of streams

SequenceInputStream represents a sequence of input streams. It allows to read from multiple of ordered streams.

package com.zetcode; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.SequenceInputStream; public class JavaInputStreamSequence < public static void main(String[] args) throws IOException < String fileName1 = "src/resources/myfile.txt"; String fileName2 = "src/resources/myfile1.txt"; String fileName3 = "src/resources/myfile2.txt"; try (InputStream is1 = new FileInputStream(fileName1); InputStream is2 = new FileInputStream(fileName2); InputStream is3 = new FileInputStream(fileName3); SequenceInputStream sis1 = new SequenceInputStream(is1, is2); SequenceInputStream sis = new SequenceInputStream(sis1, is3)) < int b = sis.read(); while (b != -1) < System.out.printf("%c", b); b = sis.read(); >System.out.println(); > > >

The example reads from three FileInputStreams .

try (InputStream is1 = new FileInputStream(fileName1); InputStream is2 = new FileInputStream(fileName2); InputStream is3 = new FileInputStream(fileName3); SequenceInputStream sis1 = new SequenceInputStream(is1, is2); SequenceInputStream sis = new SequenceInputStream(sis1, is3)) 

We define three input streams and these streams are placed into SequenceInputStreams .

int b = sis.read(); while (b != -1)

We read the data from the streams with read .

In this article we have presented the Java InputStream class.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

Источник

Class FileInputStream

A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment.

FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader .

Constructor Summary

Creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system.

Creates a FileInputStream by using the file descriptor fdObj , which represents an existing connection to an actual file in the file system.

Creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system.

Method Summary

Returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.

Returns the FileDescriptor object that represents the connection to the actual file in the file system being used by this FileInputStream .

Methods declared in class java.io.InputStream

Methods declared in class java.lang.Object

Constructor Details

FileInputStream

Creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system. A new FileDescriptor object is created to represent this file connection. First, if there is a security manager, its checkRead method is called with the name argument as its argument. If the named file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading then a FileNotFoundException is thrown.

FileInputStream

Creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system. A new FileDescriptor object is created to represent this file connection. First, if there is a security manager, its checkRead method is called with the path represented by the file argument as its argument. If the named file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading then a FileNotFoundException is thrown.

FileInputStream

Creates a FileInputStream by using the file descriptor fdObj , which represents an existing connection to an actual file in the file system. If there is a security manager, its checkRead method is called with the file descriptor fdObj as its argument to see if it's ok to read the file descriptor. If read access is denied to the file descriptor a SecurityException is thrown. If fdObj is null then a NullPointerException is thrown. This constructor does not throw an exception if fdObj is invalid . However, if the methods are invoked on the resulting stream to attempt I/O on the stream, an IOException is thrown.

Method Details

read

read

Reads up to b.length bytes of data from this input stream into an array of bytes. This method blocks until some input is available.

read

Reads up to len bytes of data from this input stream into an array of bytes. If len is not zero, the method blocks until some input is available; otherwise, no bytes are read and 0 is returned.

skip

Skips over and discards n bytes of data from the input stream. The skip method may, for a variety of reasons, end up skipping over some smaller number of bytes, possibly 0 . If n is negative, the method will try to skip backwards. In case the backing file does not support backward skip at its current position, an IOException is thrown. The actual number of bytes skipped is returned. If it skips forwards, it returns a positive value. If it skips backwards, it returns a negative value. This method may skip more bytes than what are remaining in the backing file. This produces no exception and the number of bytes skipped may include some number of bytes that were beyond the EOF of the backing file. Attempting to read from the stream after skipping past the end will result in -1 indicating the end of the file.

available

Returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. Returns 0 when the file position is beyond EOF. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes. In some cases, a non-blocking read (or skip) may appear to be blocked when it is merely slow, for example when reading large files over slow networks.

close

Closes this file input stream and releases any system resources associated with the stream. If this stream has an associated channel then the channel is closed as well.

getFD

Returns the FileDescriptor object that represents the connection to the actual file in the file system being used by this FileInputStream .

getChannel

Returns the unique FileChannel object associated with this file input stream. The initial position of the returned channel will be equal to the number of bytes read from the file so far. Reading bytes from this stream will increment the channel's position. Changing the channel's position, either explicitly or by reading, will change this stream's file position.

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

Оцените статью