使用PrintStream和FileOutputStream

时间:2017-08-29 13:08:45

标签: scala sockets file-io

我正在尝试创建套接字连接,然后将值从文件传递到套接字。

我确实设法从PrintStream传递数据到套接字,

    socketInput= "1234,112,1121"
    val ss = new ServerSocket(4141)
    val sock = ss.accept()
    val is = new BufferedInputStream(sock.getInputStream)
    val os =new PrintStream(new BufferedOutputStream(sock.getOutputStream))
    os.println(socketInput)
    os.flush()
    sock.close()

现在不是直接从Print流向socket提供输入,而是需要从csv文件中提供它。 在我阅读有关FileOutputStream的内容时,它用于将数据写入文件。 怎么样,我们可以从文件中读取并传递给套接字。

1 个答案:

答案 0 :(得分:0)

如果您的问题是如何阅读文件内容以及通过套接字发送和接收文件,您可以使用这些示例。首先,你应该运行Server.java,之后请在Client.java中更改文件的路径和名称,最后运行client。

<强> Server.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String args[]) {
        System.out.println("Server is ready:");
        int SERVER_PORT = 7005;
        ServerSocket serverSocket = null;
        Socket conn = null;
        try {
            serverSocket = new ServerSocket(SERVER_PORT, 50);
            while (true) {
                conn = serverSocket.accept();
                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line;
                while ((line = in.readLine()) != null) {
                    System.out.println(line);
                    if(line.indexOf("END") > -1) {
                        in.close();
                        break;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

<强> Client.java

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

public class Client {
    public static void main(String[] args) {
        int SERVER_PORT = 7005;
        try {
            Socket conn = new Socket("localhost",SERVER_PORT);
            PrintWriter out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream()));
            BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("/home/mohammadmehdi/development/eclipse/neonWorkSpace/javaTest/SocketTest/src/temp.txt"), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                out.println(line);
                out.flush();
            }
            out.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}