如何将jar文件的内容作为字节数组返回?

时间:2013-08-21 21:00:00

标签: java bytearray

我试图将文件的内容作为一个字节数组。

public static void main(String[] args) {

    final IServiceClient client = StorageConsumerProvider.getStorageServiceClient("dev");

    String name = new File("C:\\Storage\\Model-1.0.0.jar").getName();

    StorageObjectIdentifier objIdentifier = new StorageObjectIdentifier("Model", "1.0.0", name);

// I need to pass the bytes here
    client.createObject(objIdentifier, name.getBytes());

}

界面就像这样 -

public void createObject(StorageObjectIdentifier objIdentifier, byte[] obj)

createObject方法接受两个参数,其中一个是 - 文件内容为字节数组

我不确定如何将其作为字节数组传递?任何人都可以帮我吗?在我的情况下,该文件是一个jar文件。

4 个答案:

答案 0 :(得分:1)

您必须使用以下函数手动加载bytearray中的所有文件内容:

public final static byte[] load(FileInputStream fin) throws Exception
{
      ByteArrayOutputStream baos = new ByteArrayOutputStream();

      int readCnt = fin.read(readBuf);
      while (0 < readCnt) {
        baos.write(readBuf, 0, readCnt);
        readCnt = fin.read(readBuf);
      }

      fin.close();

      return bout.toByteArray();
  }

但是如果文件很小则有效,对于大文件,你将运行到NPE 更好的选择是改变你的接口传递InputStream而不是byte[],让intf实现者决定如何操作。

答案 1 :(得分:1)

目前您只是传递文件的名称的字节数组表示。您需要打开文件并阅读它。您可以使用FileInputStream等进行此操作,但如果您愿意使用Guava,则Files.toByteArray()可以轻松实现:

File file = new File("C:\\Storage\\Model-1.0.0.jar");
byte[] data = Files.toByteArray(file);
StorageObjectIdentifier objIdentifier =
    new StorageObjectIdentifier("Model", "1.0.0", name);

client.createObject(objIdentifier, data);

答案 2 :(得分:1)

您正在将包含文件名的字节数组传递给createObject方法。要首先传递包含文件内容的字节数组,必须将文件读入字节数组。

使用FileReader或FileInputStream,创建一个传递文件名或File对象的实例, 然后使用read()方法之一将字节读入数组。

答案 3 :(得分:1)

您可以使用BufferedInputStream将文件作为带缓冲的字节流加载。

File iFile = new File("C:\\Storage\\Model-1.0.0.jar");
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(iFile));

int read = 0;
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[1024]; // buffer size
while ((read = bis.read(buffer)) != -1) {
    os.write(buffer, 0, read);
}
bis.close();

StorageObjectIdentifier objIdentifier =
                        new StorageObjectIdentifier("Model", "1.0.0", iFile.getName());
client.createObject(objIdentifier, os.toByteArray());

或者,使用FileUtils

中的Apache Commons IO
client.createObject(objIdentifier, FileUtils.readFileToByteArray(iFile));