【问题标题】:How to read an array of bytes from a file using datainput stream, and print the array of bytes in java如何使用数据输入流从文件中读取字节数组,并在 java 中打印字节数组
【发布时间】:2014-11-06 13:43:36
【问题描述】:

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

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

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 中的内容存储到数组中。

请帮助解决这个问题

【问题讨论】:

  • buffer bs into a array bs 是一个数组
  • “我无法打印字节数组”是什么意思?你会得到哪些结果?还是你不知道如何打印数组?

标签: java arrays datainputstream


【解决方案1】:

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

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 对象的值存储在其上:

bs = content.getBytes();

提前,如果字节的打印不同,请不要担心,例如 [B@199c55a [B@faa824 这只是对象的名称,但两者的值相同。

【讨论】:

  • 我们如何将结果再次存储回字节数组
  • 如果我们需要打印该值,必须进行哪些更改
  • 这取决于您要如何打印。我的意思是,该值位于变量上,因此您可以通过多种方式调用它。当然,这里我是在一个静态块里面做的,但是很容易改变。
猜你喜欢
  • 2019-07-27
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 2011-05-15
  • 2014-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多