有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何以字符串形式访问InputStream中的数据?

我正在尝试使用socket编程创建一个安卓客户端和java服务器应用程序。我需要检索从java服务器发送的文件,但我不想在客户端将该内容写入另一个文件。相反,我想创建一个列表框,其中包含接收文件中的内容。我可以找到在文件中写入这些内容的代码,但我不知道如何以字符串的形式访问这些内容

以下是我尝试的代码:

Android客户端

client=new Socket("10.0.2.2", 7575);
writer=new PrintWriter(client.getOutputStream(),true);
writer.write(mMsg);
writer.flush();
writer.close();
InputStream is=client.getInputStream(); 
bytesread=is.read(mybytearray,0,mybytearray.length);

我改变了我的代码如下,但它不工作

 InputStream is=client.getInputStream();
 BufferedReader bf=new BufferedReader(new InputStreamReader(is));
 String value=bf.readLine();

共 (3) 个答案

  1. # 1 楼答案

    将输入流包装成BufferedReader

    BufferedReader d
              = new BufferedReader(new InputStreamReader(is));
    

    并使用^{}方法

    Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

  2. # 2 楼答案

    最好使用缓冲读取器,也可以尝试以下代码:

    在最后一条语句之后,使用byte[] "mybytearray"转换为字符串,如下所示:

    if(bytesread > 0)
        String result = new String(mybytearray);
    
  3. # 3 楼答案

    试试这个:

    InputStream is=client.getInputStream(); 
    bytesread=is.read(mybytearray,0,mybytearray.length);
    // Create a new String out of the bytes read
    String data = new String(mybytearray, 0, bytesread, CharSet);
    


    使用BufferedReader包装InputStream,并以String格式逐行读取数据(使用readLine()