使用Java而不是File在字符串中发送数据

时间:2015-04-10 10:24:17

标签: java

我是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文件的内容。实际上,该文件包含一个字符串,必须直接发送。

2 个答案:

答案 0 :(得分:0)

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

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);

  }



}

读取文件内容并将其存储到String中并传递给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);

答案 1 :(得分:0)

使用以下代码:

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();
}
相关问题