Java中的“ private static final”是什么意思?

时间:2018-09-01 02:30:10

标签: java android

我对android非常陌生,我只是在摸摸它的表面。当我浏览一些教程时,我碰到了这个类来下载文件。我能够理解其他代码,但无法理解

  private static final int  MEGABYTE = 1024 * 1024;

是吗?这真的有必要吗?如果未声明为“第一”怎么办。

下面是代码

public class FileDownloader {
    private static final int  MEGABYTE = 1024 * 1024;

    public static void downloadFile(String fileUrl, File directory){
        try {

            URL url = new URL(fileUrl);
            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
            //urlConnection.setRequestMethod("GET");
            //urlConnection.setDoOutput(true);
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            FileOutputStream fileOutputStream = new FileOutputStream(directory);
            int totalSize = urlConnection.getContentLength();

            byte[] buffer = new byte[MEGABYTE];
            int bufferLength = 0;
            while((bufferLength = inputStream.read(buffer))>0 ){
                fileOutputStream.write(buffer, 0, bufferLength);
            }
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这一定是一个非常愚蠢的问题,但我真的很好奇知道如何以及为什么?

谢谢。

3 个答案:

答案 0 :(得分:3)

MEGABYTE = 1024 * 1024MB中的平均字节数,称为兆字节

8 bits      = 1 byte
1024 bytes  = 1 kb 
1024 kb     = 1 Mb 

,并且1 Mb包含1048576。等于1024 * 1024

的字节

inputStream.read将尝试从流中读取此数量的字节并将其放入字节数组中

 data_read_as_byte      return
     > 0                number of bytes read
     < 0                  -1

 // return 0 when passed array size is 0

答案 1 :(得分:1)

/* object.price1 = 10.0 object.price2 = 9.9 object.price3 = 8.9 object.price4 = 10.1 object.name = "banana" object.type = "fruit" object.quantitySold = 0 object.dateIntroduced = "" */ let banana = object() for property in banana { object.property = property*2 } 声明意味着将该值声明为常量。它没有什么特别的,将硬编码的值作为常量只是一种很好的编码实践。出于代码可读性和可维护性的目的。

您的代码基本上是在创建 1 MB的缓冲区来下载文件。

这意味着在下载文件时,首先将1 MB下载到您的RAM中,然后将该部分复制到文件输出流(磁盘)中,并将重复此过程,直到下载完所有内容为止。请注意,如果所有内容都已下载到RAM,则设备可能会用完内存,并且应用会抛出private static final。另请注意,您可以为缓冲区选择任何值而不是1 MB。

答案 2 :(得分:1)

  
private static final int  MEGABYTE = 1024 * 1024;
         

是吗?

  

声明了一个变量finalprivatestatic

它必须要做的是,您可以在MEGABYTE类(FileDownloader)的任何方法中引用because it is private变量,无论是static还是not

如果它有declared inside any method,则scope仅在该方法之内。

如果将其作为declared without static关键字,则将无法通过static方法进行访问。您可以通过删除static关键字来自己尝试。

  
    

这真的有必要吗?如果未声明为“第一”怎么办。

  

在给定的类中,只有一个static method且此变量被声明为private,因此以这种方式声明它没有多大意义。在您的方法中声明此变量也应该很好

实例化MEGABYTES小于INTEGER.MAX_VALUE应该没问题

相关问题