首页 文章

从Android Studio Java中的文本文件中读取

提问于
浏览
6

我有一个类QuoteBank需要读取扫描仪的txt文件,但它给我一个文件未找到异常

java文件位于app / src / main / java / nate.marxBros / QuoteBank.java

txt文件位于app / src / main / assets / Quotes.txt

代码是

File file = new File("assets/QuotesMonkeyBusiness.txt");
    Scanner input = null;
    try {
        input = new Scanner(file);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

这不能像其他任何java程序一样工作吗?但它给文件找不到异常

我在这个网站上尝试了很多东西,比如Android Studio Reading from Raw Resource Text File,但是这个方法不起作用,因为我不知道如何传递上下文

谢谢你的帮助

更新的代码

public class QuoteBank {
private ArrayList<ArrayList<QuoteBank>> bank;
private Context mContext;
private ArrayList<QuoteQuestion> monkeyBuisness;


public QuoteBank(Context context){
    mContext = context;
    InputStream is = null;
    try {
        is = mContext.getAssets().open("QuotesMonkeyBusiness.txt");
    } catch (IOException e) {
        e.printStackTrace();
    }

    ArrayList<QuoteQuestion> monkeyBuisness = parseFileToBank(is);
}

主要活动

public class MainActivity extends ActionBarActivity {
QuoteBank b = new QuoteBank(MainActivity.this);

3 回答

  • 0

    你应该有 MainActivity.java 或某些 Activity 来实例化 QuoteBank . 您希望构造函数接受上下文的参数:

    QuoteBank.java 中设置一个私有变量:

    private Context mContext;
    

    设置构造函数:

    public QuoteBank(Context context) {
       this.mContext = context;
    }
    

    然后在你的活动中实例化它,

    QuoteBank quoteBank = new QuoteBank(context);
    

    可以通过 this 命令在活动中调用上下文变量,或者在 Activity.this 中使用您的活动名称替换"Activity" . 或者,如果您在片段内,则可以从 onCreateView(...) 方法中的 View 对象获取上下文 . 通常通过调用 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");
    

    QuoteBank 作为单例实例也可能有意义,这可能会提高效率,尽管这完全取决于您的要求,可能是这样的:

    List<String> allTextLines = QuoteBank.readFromFile(context, path_to_file);
    

    然后在你的 QuoteBank.java 课程中,您可以使用如下方法:

    /**
    * Created by AndyRoid on 5/23/15.
    */
    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;
    }
    

    }

    然后在我的 MainActivity.java 课程中我有以下内容:

    /**
     * Created by AndyRoid on 5/23/15.
     */
    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;
    
    @Override
    protected 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);
    }
    
    @Override
    public 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;
    }
    
    @Override
    public 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);
    }
    }
    

    这是我的项目结构:

    enter image description here

    这是我从随机数据库下载的 adventur.txt 文件:

    file

    这是我的日志输出:

    enter image description here


    UPDATE: Why you should not use a Scanner in Android

    从官方文档:

    http://developer.android.com/reference/java/util/Scanner.html

    这个类没有它看起来那么有用 . 在机器之间进行通信效率非常低;你应该使用JSON,protobufs甚至XML . 非常简单的用法可能会脱离split(String) . 对于来自人类的输入,使用特定于语言环境的正则表达式使其不仅昂贵而且有些不可预测 . Scanner类不是线程安全的 .


    FINAL NOTE:

    我强烈建议您阅读此处使用的所有对象的文档,以便您了解该过程 .

  • 5

    Context.getResources().getAssets().open("QuotesMonkeyBusiness.txt"); 返回 InputStream 其余的你可以从那里拿走它

    Edit

    因为我不知道如何传递Context

    Context 实际上到处都是如果你有一个 View 你可以得到 Context ,如果你 Activity 你可以得到 Context 所以找到它

    希望能帮助到你

  • 1

    一个简单问题的简单答案 .

    private String readFile()
    {
        String myData = "";
        File myExternalFile = new File("assets/","log.txt");
        try {
            FileInputStream fis = new FileInputStream(myExternalFile);
            DataInputStream in = new DataInputStream(fis);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
    
            String strLine;
            while ((strLine = br.readLine()) != null) {
                myData = myData + strLine + "\n";
            }
            br.close();
            in.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return myData;
    }
    

    只需使用函数读取外部文件即可 .

相关问题