Java 为什么将此字节数组初始化为 1024
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6557799/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
why initialize this byte array to 1024
提问by b10hazard
I'm relatively new to Java and I'm attempting to write a simple android app. I have a large text file with about 3500 lines in the assets folder of my applications and I need to read it into a string. I found a good example about how to do this but I have a question about why the byte array is initialized to 1024. Wouldn't I want to initialize it to the length of my text file? Also, wouldn't I want to use char
, not byte
? Here is the code:
我对 Java 比较陌生,我正在尝试编写一个简单的 android 应用程序。我的应用程序的资产文件夹中有一个大约 3500 行的大文本文件,我需要将它读入一个字符串。我找到了一个关于如何执行此操作的好示例,但我有一个关于为什么将字节数组初始化为 1024 的问题。我不想将其初始化为我的文本文件的长度吗?另外,我不想使用char
,不是byte
吗?这是代码:
private void populateArray(){
AssetManager assetManager = getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open("3500LineTextFile.txt");
} catch (IOException e) {
Log.e("IOException populateArray", e.getMessage());
}
String s = readTextFile(inputStream);
// Add more code here to populate array from string
}
private String readTextFile(InputStream inputStream) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
inputStream.length
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
Log.e("IOException readTextFile", e.getMessage());
}
return outputStream.toString();
}
EDIT: Based on your suggestions, I tried this approach. Is it any better? Thanks.
编辑:根据您的建议,我尝试了这种方法。有没有更好的?谢谢。
private void populateArray(){
AssetManager assetManager = getAssets();
InputStream inputStream = null;
Reader iStreamReader = null;
try {
inputStream = assetManager.open("List.txt");
iStreamReader = new InputStreamReader(inputStream, "UTF-8");
} catch (IOException e) {
Log.e("IOException populateArray", e.getMessage());
}
String String = readTextFile(iStreamReader);
// more code here
}
private String readTextFile(InputStreamReader inputStreamReader) {
StringBuilder sb = new StringBuilder();
char buf[] = new char[2048];
int read;
try {
do {
read = inputStreamReader.read(buf, 0, buf.length);
if (read>0) {
sb.append(buf, 0, read);
}
} while (read>=0);
} catch (IOException e) {
Log.e("IOException readTextFile", e.getMessage());
}
return sb.toString();
}
采纳答案by JB Nizet
This example is not good at all. It's full of bad practices (hiding exceptions, not closing streams in finally blocks, not specify an explicit encoding, etc.). It uses a 1024 bytes long buffer because it doesn't have any way of knowing the length of the input stream.
这个例子一点都不好。它充满了不好的做法(隐藏异常,不关闭 finally 块中的流,不指定显式编码等)。它使用 1024 字节长的缓冲区,因为它无法知道输入流的长度。
Read the Java IO tutorialto learn how to read text from a file.
阅读Java IO 教程以了解如何从文件中读取文本。
回答by Kazuo
You are reading the file into a buffer of 1024 Bytes. Then those 1024 bytes are written to outputStream. This process repeats until the whole file is read into the outputStream. As JB Nizet mentioned the example is full of bad practices.
您正在将文件读入 1024 字节的缓冲区。然后将这 1024 个字节写入 outputStream。这个过程一直重复,直到整个文件被读入 outputStream。正如 JB Nizet 提到的,这个例子充满了不好的做法。
回答by Lynch
To read from a file I usaully use a Scanner and a StringBuilder.
为了从文件中读取,我通常使用 Scanner 和 StringBuilder。
Scanner scan = new Scanner(new BufferedInputStream(new FileInputStream(filename)), "UTF-8");
StringBuilder sb = new StringBuilder();
while (scan.hasNextLine()) {
sb.append(scan.nextLine());
sb.append("\n");
}
scan.close
return sb.toString();
Try to throw your exceptions instead of swallowing them. The caller must know there was a problem reading your file.
尝试抛出您的异常而不是吞下它们。呼叫者必须知道读取您的文件时出现问题。
Edit:Also note that using a BufferedInputStream is important. Otherwise it will try to read bytes by bytes which can be slow.
编辑:另请注意,使用 BufferedInputStream 很重要。否则它会尝试逐字节读取可能很慢的字节。
回答by Stephen C
Wouldn't I want to initialize it to the length of my text file? Also, wouldn't I want to use char, not byte?
我不想将它初始化为我的文本文件的长度吗?另外,我不想使用字符而不是字节吗?
Yes, and yes ... and as other answers have said, you've picked an example with a number of errors in it.
是的,是的......正如其他答案所说,您选择了一个包含许多错误的示例。
However, there is a theoretical problem doing both; i.e. setting the buffer length to the file length andusing a character buffer rather than a byte buffer. The problem is that the file size is measured in bytes, but the size of the buffer needs to be measured in characters. This is normally fine, but it is theoretically possiblethat you will need more characters than the file size in bytes; e.g. if the input file used a 6 bit character set and packed 4 characters into 3 bytes.
但是,两者都存在理论上的问题;即将缓冲区长度设置为文件长度并使用字符缓冲区而不是字节缓冲区。问题是文件大小是用字节来衡量的,而缓冲区的大小需要用字符来衡量。这通常没问题,但理论上可能需要比文件大小(以字节为单位)更多的字符;例如,如果输入文件使用 6 位字符集并将 4 个字符打包成 3 个字节。