想试着用Java封装一个readChars()方法
功能和readUTF()功能类似
输出数据流中用writeChars()方法写入的字符串
如何用Java封装一个自定义的方法?
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
6条回答 默认 最新
Watch the clown 2023-06-17 19:44关注基本问题。写一个案例:
public static String readChars(DataInputStream dis) throws IOException { int len = dis.readInt(); char[] chars = new char[len]; for (int i = 0; i < len; i++) { chars[i] = dis.readChar(); } return new String(chars); } String str = "test!"; ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); dos.writeInt(str.length()); dos.writeChars(str); byte[] bytes = baos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); DataInputStream dis = new DataInputStream(bais); String result = readChars(dis); System.out.println(result);本回答被题主选为最佳回答 , 对您是否有帮助呢?评论 打赏 举报 编辑记录解决 2无用