使用java.nio时引发IllegalArgumentException

时间:2019-04-15 19:26:16

标签: java android nio

尝试通过url下载文件。为此使用java.nio库。上面的代码非常适合sdk 24及以上版本,但适用于android sdk 23及以下版本的IllegalArgumentException。尝试传输数据时出现错误。亲爱的朋友,您能说清楚是哪个问题。

    private void downloadFile(final String itemUrl) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                ReadableByteChannel readableByteChannel = null;
                FileOutputStream fOutStream = null;

                String root = 
                getApplicationContext().getApplicationInfo().dataDir;
                File myDir = new File(root + "/downloadedSongs");
                if (!myDir.exists()) {
                myDir.mkdirs();
                }

                File file = new File(myDir, itemTitle);
                if (file.exists()) {
                    file.delete();
                }

                try {
                    URL url = new URL(itemUrl);
                    readableByteChannel = 
                    Channels.newChannel(url.openStream());
                    fOutStream = new FileOutputStream(file);
      fOutStream.getChannel().transferFrom(readableByteChannel, 0, Long.MAX_VALUE);

                } catch (IOException e) {
                    orderAction = Enums.OrderAction.Delete;
                } catch (IllegalArgumentException e) {
                    orderAction = Enums.OrderAction.Delete;
                    Crashlytics.logException(e);
                } finally {
                    try {
                        if (fOutStream != null) {
                            fOutStream.close();
                        }
                        if (readableByteChannel != null) {
                           readableByteChannel.close();
                        }
                    } catch (IOException ioExObj) {
                        orderAction = Enums.OrderAction.Delete;
                    }
                    closeNotification(orderAction);
                }
            }
    }).start();
}

enter image description here

致命异常:java.lang.IllegalArgumentException:position = 0 count = 922337203685477575807在java.nio.FileChannelImpl.transferFrom(FileChannelImpl.java:370)在am.itsoft.youtomp3.services.DnlService $ 1.run(DnlService.java :169),位于java.lang.Thread.run(Thread.java:818)

1 个答案:

答案 0 :(得分:0)

原因在于此参数:Long.MAX_VALUE

正确的代码:

FileChannel destChannel = fOutStream.getChannel();
long blockSize;
if (Build.VERSION.SDK_INT > 23) {
  long blockSize = Long.MAX_VALUE;
} else {
  long blockSize = 8*1024;
}
long position = 0;
long loaded;
while ((loaded = destChannel.transferFrom(readableByteChannel, position, blockSize)) > 0) {
   position += loaded;
}