开发者社区> 问答> 正文

java中字符串转换为字节数组请问用什么方法

java中字符串转换为字节数组请问用什么方法,字符串返回字节数组怎么做?

展开
收起
蛮大人123 2016-05-26 16:06:39 2437 0
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    java中String类有getBytes方法,可以将字符串转成字节数组。字节数组可以直接写入到输出流中,如写入文件输出流中,Socket输出流中等。
    实例代码:

        public static void main(String[] args) {
            String text = "helloworld";
            byte[] bytes = text.getBytes();
            try {
                OutputStream out  = new FileOutputStream(new File("src/text.txt"));
                out.write(bytes);
                out.flush();
                out.close();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    网络通信中都是用的字节数据的,所以有时候需要把字符串转成byte数组进行数据发送的。

    2019-07-17 19:16:26
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载