簡體   English   中英

使用流在Java中傳輸數據

[英]Transferring data in Java using streams

我一直在閱讀有關I / OJava教程,以了解流及其正確用法。 假設我有兩個連接的設備,兩個設備上都有一個InputStreamOutputStream 如何在兩者之間傳輸數據?

例如,如果我想在一台設備上向另一台設備發送一堆單詞,然后將它們打印到屏幕上。 那將如何工作?

public class Device1 {
    // assuming connectedDevice is something
    String[] words = new String()[]{"foo", "bar", "baz"};
    OutputStream os = connectedDevice.getOutputStream();
    InputStream is = connectedDevice.getInputStream();
    /*
        How to write to output stream?
    */
}

public class Device2 {
    // assuming connectedDevice is something
    ArrayList<String> words = new ArrayList<String>();
    OutputStream os = connectedDevice.getOutputStream();
    InputStream is = connectedDevice.getInputStream();
    /*
        How can I somehow get the words using `read()` and `put()`
        them into the ArrayList for use?
    */
}

也許我做錯了所有這一切。 在此先感謝您對理解的任何幫助。

這取決於設備的連接方式。 例如,它們可能通過TCP或共享文件系統連接。

如果要專注於流,請創建使用文件系統的應用程序。 然后,使用FileOutputStreamFileInputStream了解流API。

如果您專注於網絡,那么您也將要學習網絡教程

如果您只想發送字符,請使用書寫側的OutputStreamWriter和讀取側的InputStreamReader來包裝流。 您可以編寫整個字符串,然后一次讀取一個字符並進行打印。 如果需要非常小心,則應為兩者都選擇固定的字符編碼。

如果要發送整個簡單對象(如String ,則可以使用DataOutputStream / DataInputStream (對於字符串,請使用UTF方法。)

如果您想變得更復雜,則需要使用ObjectOutputStreamObjectInputStream對對象進行序列化/反序列化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM