我對Java比較陌生,我試圖編寫一個簡單的android應用程序。我的應用程序的資產文件夾中有大約3500行的大文本文件,我需要將它讀入字符串中。我找到了一個很好的例子,說明如何做到這一點,但我有一個問題,爲什麼字節數組被初始化爲1024.我不想將它初始化爲我的文本文件的長度?另外,我不想使用char
,而不是byte
?這裏是代碼:爲什麼初始化這個字節數組爲1024
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();
}
編輯:根據你的建議,我試過這種方法。它更好嗎?謝謝。
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();
}
沒錯。考慮一下:如果你的字節數組長度與輸入流的長度一樣長,並且文件的大小應該是4GB,那麼你將把所有4GB的文件加載到RAM中,從而減慢計算機的速度,可能導致系統崩潰。這就是爲什麼您一次讀取1024個字節的原因,以最大限度地減少陣列使用的內存量。 – OzzyTheGiant