从java服务器发送整数或字符串

时间:2011-08-19 20:02:33

标签: java android sockets inputstream

我有一个java服务器,可以发送任何类型的文件,但我无法管理发送字符串或整数。

以下是文件发送方式的示例。

File f = new File("/Users/Large/Downloads/android.jpg");
FileInputStream fis = null;
int size = (int)f.length();
byte[] bytes = new byte[size];
fis = new FileInputStream( f );
fis.read( bytes );

System.out.println("entro...");
out.write( bytes );
out.flush();

1 个答案:

答案 0 :(得分:2)

尝试使用StringByteBuffer类的示例替换您对out.write(bytes)的通话。

// A string ("Hello, World").
out.write("Hello, World".getBytes());

// An integer (123).
out.write(ByteBuffer.allocate(4).putInt(123).array());

请注意,在某些时候,您需要关注endiannesscharacter encoding,以便在另一端以可靠的方式读取这些值。