在Java中以字符串而不是文件发送数据

在Java中以字符串而不是文件发送数据,java,Java,我是Java新手。我需要在Java中通过套接字发送字符串。 到目前为止,代码如下所示 public static void main(String [] str) { String temp; try { inputStream = new BufferedReader(new FileReader("Z:\\ABC.txt")); String inLine = inputStream.readLine(); S

我是Java新手。我需要在Java中通过套接字发送字符串。 到目前为止,代码如下所示

public static void main(String [] str)
{

    String temp;

    try
    {


        inputStream = new BufferedReader(new FileReader("Z:\\ABC.txt"));
        String inLine = inputStream.readLine();

        System.out.println("Read String" + inLine);
        int k[] = new int[(inLine.length())/2];
        byte b[] = new byte[(inLine.length())/2];

必须以字符串形式发送文件ABC.txt的内容。实际上,该文件包含一个字符串,必须直接发送相同的内容。

此代码将帮助您获得解决方案

import java.net.*;
import java.io.*;

public class Operation
{
 static String serverName = "xxx.xxx.x.x";//ipaddress
  static int port = 9999;

public void writeTo(String fileContent)
{

     try
  {
     System.out.println("Connecting to " + serverName+ " on port " + port);
     Socket client = new Socket(serverName, port);
     System.out.println("Just connected to " + client.getRemoteSocketAddress());

     OutputStream outToServer = client.getOutputStream();
     DataOutputStream out = new DataOutputStream(outToServer);

     out.writeUTF(fileContent);


     client.close();
  }catch(IOException e)
  {
    // e.printStackTrace();
    System.out.println(e);

  }



}
读取文件内容并将其存储到字符串中,然后传递给writeTo()

阅读

    BufferedReader br=new BufferedReader(new FileReader(file_name));
    try{

        String Myplaintext="";
        String currentline="";
        while((currentline=br.readLine())!=null)
        {
            Myplaintext=Myplaintext+" "+currentline.toString();

        }
打电话

 writeTo(Myplaintext);
使用以下代码:

Socket socket = null;
try {
    Socket socket = new Socket("ip address", portNo);
    OutputStream os =socket.getOutputStream();
    File file = new File("Z:\\ABC.txt");
    os.write(Files.readAllBytes(file.toPath()));
} catch (IOException e) {
    System.err.print(e);
} catch (UnknownHostException e) {
    System.err.print(e);
} finally {
    if(socket!= null)
       socket.close();
}

问题是什么?需要通过套接字直接发送字符串,而不是从文件中读取