gpt4 book ai didi

java - 为文件传输分配新的byte []时,如何防止OutOfMemory错误?

转载 作者:行者123 更新时间:2023-12-04 20:13:42 33 4
gpt4 key购买 nike

我试图读取文件以便通过Wear App发送文件,但出现了OutOfMemory异常。

File file = new File(filePath);
final FileInputStream fileInputStream = new FileInputStream(file);
byte fileContent[] = new byte[(int) file.length()]; //***BOMBS HERE***
fileInputStream.read(fileContent);
fileInputStream.close();
Asset programDataAsset = Asset.createFromBytes(fileContent);


异常指出以下内容:

java.lang.OutOfMemoryError: Failed to allocate a 31150467 byte allocation with 2097152 free bytes and 16MB until OOM
at com.rithmio.coach.wear.TransferService.sendAssetToMobile(TransferService.java:110)
at com.rithmio.coach.wear.TransferService.onHandleIntent(TransferService.java:84)
at com.rithmio.coach.wear.TransferService$1.run(TransferService.java:60)
at java.lang.Thread.run(Thread.java:818)

最佳答案

让我们使用ChannelApi解决此问题。我们也不必担心我在评论中说过的内容。 Google考虑周全,并提出了一种方便的文件发送方法。 public abstract PendingResult sendFile (GoogleApiClient client, Uri uri)

private String pickBestNodeId(List<Node> nodes) {
String bestNodeId = null;
// Find a nearby node or pick one arbitrarily
for (Node node : nodes) {
if (node.isNearby()) {
return node.getId();
}
bestNodeId = node.getId();
}
return bestNodeId;
}

public boolean send(File f) {
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)
// Request access only to the Wearable API
.addApi(Wearable.API)
.build();
mGoogleApiClient.blockingConnect();
Channel channel = openChannel(mGoogleApiClient, pickBestNodeId(Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).await()), "/your/arbitrary/application/specific/path/").await(); //NOTE THE PATH IS ARBITRARY, IT CAN BE WHATEVER YOU WANT. IT DOES NOT POINT TO ANYTHING, AND CAN EVEN BE LEFT WITH WHAT I HAVE.
boolean didSend = channel.sendFile(mGoogleApiClient, f.toURI()).await().isSuccess();
channel.close(mGoogleApiClient);
mGoogleApiClient.disconnect();
return didSend;
}


注意:这使用阻塞方法,并且不应在ui线程中运行。

如果您希望这些调用是非阻塞的,则应省略我对 PendingResult.await()的使用,并将结果回调设置为 PendingResult。可以通过 setResultCallback(ResultCallback callback)设置回调。

关于java - 为文件传输分配新的byte []时,如何防止OutOfMemory错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32061576/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com