我正在尝试读取文本文件并将每行文本保存到ArrayList中。我尝试了各种方法,包括FileInputStream和BufferedReader。这是目前让我最接近我想要做的代码
try {
InputStream is = getResources().openRawResource(R.File.txt);
BufferedReader bufferedReader = new BufferedReader(new FileReader("File.txt"));
String line;
while((line = bufferedReader.readLine()) != null)
{
allText.add(line);
}
bufferedReader.close();
}
catch(IOException e)
{
}
allText
是先前实例化的ArrayList。现在文件保存在/ res中,我得到一个"无效的资源目录警告"。我想知道在哪里正确保存文件以及如何从中读取文件。
答案 0 :(得分:3)
该行应为
InputStream is = getResources().openRawResource(R.File.txt);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
您为资源文件创建了InputStream
,并使用BufferedReader
从创建的流中读取。
答案 1 :(得分:1)
getAssets()
方法BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("File.txt"), "UTF-8"));
String myData = reader.readLine();
while (myData != null) {
myData = reader.readLine();
}
} catch (IOException e) {
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}
/res/raw
文件夹 InputStream fileInputStream = getResources().openRawResource(R.raw.File);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte buf[] = new byte[1024];
int len;
try {
while ((len = fileInputStream .read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.close();
fileInputStream .close();
} catch (IOException e) {
}
return outputStream.toString();
}