有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在sd上写入文件时获得文件大小?

请帮帮我。我需要得到完整的文件大小,并且已经写入while循环。我需要这个来设置进度条的进度。 这是我的代码:

            try {
            URL u = new URL(imgUrl);
              InputStream is = u.openStream();

              DataInputStream dis = new DataInputStream(is);

              byte[] buffer = new byte[1024];
              int length;
              File root = new File(Environment.getExternalStorageDirectory()
                      + File.separator + "saved" + File.separator);
                    root.mkdirs();
                    String name = "" + System.currentTimeMillis() + ".jpg";
                    File sdImageMainDirectory = new File(root, name);
                    Uri outputFileUri = Uri.fromFile(sdImageMainDirectory);
                    OutputStream output = new FileOutputStream(sdImageMainDirectory);


            while ((length = dis.read(buffer))>0) {
                  output.write(buffer, 0, length);
            }

            } catch (MalformedURLException mue) {
                  Log.e("SYNC getUpdate", "malformed url error", mue);
                } catch (IOException ioe) {
                  Log.e("SYNC getUpdate", "io error", ioe);
                } catch (SecurityException se) {
                  Log.e("SYNC getUpdate", "security error", se);
                }

共 (1) 个答案

  1. # 1 楼答案

    如果您想获得已经写入的字节数,请使用以下方法:

    在while循环之前添加一个名为writtenBytes的变量:

    long writtenBytes = 0L;
    

    然后,在while循环中,添加以下代码:

    while ((length = dis.read(buffer))>0) {
        output.write(buffer, 0, length);
        writtenBytes += length;
    }
    

    要在下载文件之前获得文件大小,您必须将下载代码更改为:

    URL url = new URL(imgUrl);
    URLConnection connection = url.openConnection();
    connection.connect();
    
    int fileLength = connection.getContentLength();
    InputStream inputStream = url.openStream();
    
    DataInputStream dis = new DataInputStream(is);