Original link Author: Jakob Jenkov Translator: Li Jing ([email protected]) proofreading: Fang Fei
The content of the network in Java is more or less beyond the scope of Java IO. More about the Java network is explored in my Java Web tutorial. But since the network is a common source of data and data flow destinations, and because you use the Java IO API to communicate over a network connection, this article will briefly cover network applications.
When a network connection is established between two processes, they communicate in the same way as they do the file: they use InputStream to read data and write data using OutputStream. In other words, the Java Network API is used to establish a network connection between different processes, while Java IO is used to exchange data between processes that have established a connection.
Basically means that if you have a piece of code that can write some data to a file, it can also be easily written to a network connection. All you need to do is write the data using InputStream instead of FileInputStream in your code. Because FileInputStream is a subclass of InputStream, there is no problem with doing so. (The translator Note: This should be outputstream and FileOutputStream)
In fact, the read operation of the file is similar, a component with the ability to read the file data, the same can easily read the data in the network connection. Just make sure that the components that read the data are based on InputStream and not fileinputstream.
Here is a simple code example:
03 |
public static void main(String[] args) { |
04 |
InputStream inputStream = new FileInputStream( "c:\\myfile.txt" ); |
08 |
public static void process(InputStream input) throws IOException { |
09 |
//do something with the InputStream |
In this example, the process () method does not care about the input stream of the InputStream parameter, whether it comes from a file or a network (the example shows only the version of the input stream from the file). The process () method only operates on InputStream.
original articles, reproduced please specify: reproduced from the Concurrent programming network –ifeve.com This article link address: Java IO: Network
Java IO: Network