Java 读取文本文件方法
我是一个安卓新手,所以如果这看起来很琐碎,并且帖子很长,我深表歉意。我在谷歌上搜索过等等,但我能找到的唯一android参考资料似乎都是参考的Java 读取文本文件方法,java,android,file,text,Java,Android,File,Text,我是一个安卓新手,所以如果这看起来很琐碎,并且帖子很长,我深表歉意。我在谷歌上搜索过等等,但我能找到的唯一android参考资料似乎都是参考的 InputStream is = getAssets().open("read_asset.txt"); int size = is.available(); // Read the entire asset into a local byte buffer. byte[] buffer = new by
InputStream is = getAssets().open("read_asset.txt");
int size = is.available();
// Read the entire asset into a local byte buffer.
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
我尝试在我的类中使用它,但即使在导入java.io.InputStream之后;它在getAssets()上出错
我正在尝试使用listview的rowId单击;
打开一个文本文件(取决于rowId值),
逐行读取文件,
生成前16个字符的字符串数组,以此类推
然后使用数组填充下一个活动的listview
String[] sectID = null; //to be loaded in listview
switch (rowId){
case 0://custom, go to section input screen
case 1:
readSectionFile s = new readSectionFile("Sect_US.dat");
sectID=s.arrayShapesAll();
我的readSectionFile类(摘录)是
代码不工作,在readSectionFile s=new readSectionFile(“Sect_US.dat”)时崩溃
另外,在readSectionFile代码中,buf的第二个实例生成一个Eclipse错误,请求try,catch块,而第一个实例被接受
我的问题是,,
我是否要正确打开此文本文件(在/assets中)?
第二次使用buf有什么问题?getAssets()是活动中的一个方法。如果试图从其他类调用getAssets(),请将活动的上下文传递给要调用该方法的类,然后调用context.getAssets()。getAssets()是活动中的一个方法。如果试图从其他类调用getAssets(),请将活动的上下文传递给要调用该方法的类,然后调用context.getAssets()。您编写了:
我是否要正确打开此文本文件(在/assets中)
一种选择是将文本文件放置在res
下名为raw
的目录中,并使用openrawsource(…)
将其读入字符串
假设在raw
目录中有一个名为my\u text\u file
的文本文件
String myText = readTextFileFromResource(context, R.raw.my_text_file);
在哪里
你写道:
我是否要正确打开此文本文件(在/assets中)
一种选择是将文本文件放置在res
下名为raw
的目录中,并使用openrawsource(…)
将其读入字符串
假设在raw
目录中有一个名为my\u text\u file
的文本文件
String myText = readTextFileFromResource(context, R.raw.my_text_file);
在哪里
private String readTextFileFromResource(Context context, int resourceId){
StringBuilder fileContents = new StringBuilder();
try{
InputStream inputStream = context.getResources().openRawResource(resourceId);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String nextLine;
while((nextLine = bufferedReader.readLine()) != null){
fileContents.append(nextLine);
fileContents.append('\n');
}
}catch(IOException e){
//handle
}catch(Resources.NotFoundException nfe){
//handle
}
return fileContents.toString();
}