【问题标题】:open .txt file in activity在活动中打开 .txt 文件
【发布时间】:2012-10-26 07:32:09
【问题描述】:

是否可以在活动中打开 .txt 文件或显示 .txt 文件的内容?我的项目真的需要它。在我的项目中,我正在制作可扩展列表视图,它在父列表中显示单元,在子列表中显示章节。一旦选择了孩子,选定的孩子将打开相应的 .txt 文件。有没有可能这样做。请对此提出一些建议。

【问题讨论】:

    标签: android


    【解决方案1】:

    你可以让TextView在Activity中显示文本,在TextView上设置文本使用setText(CharSequence)方法。

    要从 .txt 文件中读取文本,请使用以下方法:

    FileInputStream fis=null;
    final StringBuffer buffer= new StringBuffer();
    
    try {
        fis = openFileInput("fileName.txt");
        DataInputStream dataIO = new DataInputStream(fis);
        String strLine = null;
    
        if ((strLine = dataIO.readLine()) != null) {
            buffer.append(strLine);
        }
    
        dataIO.close();
        fis.close();
    }
    catch  (Exception e) {  
    }
    

    使用

    textView.setText(buffer.toString());
    

    在活动中显示。

    【讨论】:

    • 相同的sn-p代码是here
    【解决方案2】:

    是的。

    您只需要一个File 并阅读它。只需使用来自 apache.org 的 Commons IO 库

    //file located directly on SD root.
    File myFile = new File(Environment.getExternalStorageDirectory(), "file.txt"); 
    String contents = FileUtils.readFileToString(myFile);
    

    之后,只需使用 myTextView.setText(contents); 之类的东西将文本设置为 TextView

    下载 Commons IO 库here

    【讨论】:

      【解决方案3】:

      我认为显示一个带有 textview 的 xml 文件并设置 textview 以显示您想要显示的任何内容都可以解决问题。

          textview.setText(open file you want to read from here);
      

      要打开文件,您应该使用缓冲读取器和 IO 流。

      【讨论】:

        猜你喜欢
        • 2017-05-13
        • 1970-01-01
        • 1970-01-01
        • 2021-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多