首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用datainput流从文件中读取字节数组,并在java中打印字节数组

如何使用datainput流从文件中读取字节数组,并在java中打印字节数组
EN

Stack Overflow用户
提问于 2014-11-06 13:43:36
回答 1查看 258关注 0票数 0

我已经将一个字节数组byte[] testByte; testByte = new byte[]{3,4}存储到了一个文件中,现在我需要从文件中读取并将字节数组分配给一个变量并打印出来。

我已经完成了以下代码,但无法打印字节数组

代码语言:javascript
复制
public static void main(String[] args) throws IOException {

  InputStream is = null;
  DataInputStream dis = null;

  try{
     // create input stream from file input stream
     is = new FileInputStream("c:\\test.txt");

     // create data input stream
     dis = new DataInputStream(is);

     // count the available bytes form the input stream
     int count = is.available();

     // create buffer
     byte[] bs = new byte[count];

     // read data into buffer
     dis.read(bs);

              }

现在,如何将缓冲区bs中的内容存储到数组中。

请帮我解决这个问题

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-11-06 16:56:11

可以使用bs存储new String缓冲区的内容。

代码语言:javascript
复制
public static void main(String[] args) throws IOException {

      InputStream is = null;
      DataInputStream dis = null;
      int count = 0;
      byte[] bs = null;
      String content = "";

      try{

         is = new FileInputStream("C:\\test.txt");

         dis = new DataInputStream(is);

         count = is.available();

         bs = new byte[count];

         dis.read(bs);

// here is a variable that contains the buffer content as a String
         content = new String(bs);
      } catch (IOException e) {

      } finally {
          is.close();
          dis.close();
      }
      System.out.println(content);
}

编辑(回复注释):当我们创建new String()时,我们用byte[]值实例化一个新字符串。但是,由于您已经有了一个字节数组,所以您可以使用以下方法再次将String对象的值存储在上面:

代码语言:javascript
复制
bs = content.getBytes();

预先,如果字节的打印是不同的,比如[B@199c55a [B@ same 824--它只是给对象的名称,但两者的值是相同的),请不要担心。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26781005

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档