繁体   English   中英

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

[英]What does “private static final” mean in Java?

我对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(); } } } 

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

提前致谢。

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

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

1 Mb包含1048576 等于1024 * 1024字节

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

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

 // return 0 when passed array size is 0

private static final声明意味着将该值声明为常量 它没有什么特别的,将硬编码的值作为常量只是一种很好的编码实践。 出于代码可读性和可维护性的考虑。

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

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

 private static final int MEGABYTE = 1024 * 1024; 

有吗?

声明了一个finalprivatestatic变量

它是什么必然做的是,你可以参考MEGABYTE变量的任何方法中FileDownloader类( because it is private ),无论是staticnot

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

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

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

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

实例化MEGABYTES小于INTEGER.MAX_VALUE要细

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM