您应该有一个
MainActivity.java或一些`Activity实例化QuoteBank。您可能希望构造函数采用context参数:
在中设置一个私有变量QuoteBank.java:
private Context mContext;
Setup up the constructor:
public QuoteBank(Context context) { this.mContext = context;}Then instantiate it in your activity,
QuoteBank quoteBank = new QuoteBank(context);
可以通过
this命令在活动中调用上下文变量,也可以在
Activity.this其中用活动名称替换“ Activity”。
另外,如果您位于片段中,则可以从方法View内部的对象获取上下文onCreateView(…)。通常通过致电
view.getContext()。
现在,在获取资产的方法中,可以使用上下文:
InputStream is = mContext.getAssets().open("QuotesMonkeyBusiness.txt")由于您使用的是android studio,因此您可以创建一个
main(String[] args) {...}方法并运行该方法,也可以只启动模拟器并使用它Log.d(...)来显示文件的输出。
另外,您也可以使用以下方法:
AssetManager am = mContext.getAssets();InputStream is = am.open("QuotesMonkeyBusiness.txt");It might also make sense to have
QuoteBankas a singleton instance, that
might increase efficiency although it all depends on your requirements, maybe
something like:
List<String> allTextLines = QuoteBank.readFromFile(context, path_to_file);
And then in your
QuoteBank.javaclass you can have a method like so:
public class QuoteBank {private Context mContext;public QuoteBank(Context context) { this.mContext = context;}public List<String> readLine(String path) { List<String> mLines = new ArrayList<>(); AssetManager am = mContext.getAssets(); try { InputStream is = am.open(path); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; while ((line = reader.readLine()) != null) mLines.add(line); } catch (IOException e) { e.printStackTrace(); } return mLines;}}
and then in my
MainActivity.javaclass I have the following:
public class MainActivity extends AppCompatActivity {public static final String TAG = MainActivity.class.getSimpleName();public static final String mPath = "adventur.txt";private QuoteBank mQuoteBank;private List<String> mLines;@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mQuoteBank = new QuoteBank(this); mLines = mQuoteBank.readLine(mPath); for (String string : mLines) Log.d(TAG, string);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item);}}UPDATE: Why you should not use a Scanner in Android
From the official documentation:
http://developer.android.com/reference/java/util/Scanner.html
此类并不像看起来的那样有用。
机器之间的通信效率非常低;您应该
为此使用JSON,protobufs甚至XML 。非常简单的用法可能会与split(String)脱节。对于
人类的输入,特定于语言环境的正则表达式的使用不仅使其
昂贵,而且有些不可预测。Scanner类不是线程
安全的。
最后提示:
我强烈建议您阅读此处使用的所有对象的文档,
以便您了解过程。



