【问题标题】:How to output contents of raw files如何输出原始文件的内容
【发布时间】:2011-01-04 17:23:59
【问题描述】:

我正在阅读有关管理应用程序资源的一章,但在以下方面遇到了一些麻烦:

"将原始文本文件资源添加到 Droid1 项目中。使用 openRawResourse() 方法创建 InputStream 对象并读取文件。使用 Log.v() 方法输出文件内容。重新运行应用程序并查看结果。”

首先,我右键单击 res 文件夹,创建了一个新的 raw 文件夹并将一个 txt 文件从我的桌面拖到其中(认为这没问题,找不到其他导入文件的方法)。

然后我写了这两行:

InputStream iFile = getResources().openRawResource(R.raw.textfile);
Log.v(TAG, iFile);

但是我得到了错误:

“Log类型中的方法v(String, String)不适用于参数(String, InputStream)”

不知道该怎么做...任何建议。谢谢。

【问题讨论】:

    标签: logging resources inputstream


    【解决方案1】:

    由于错误表明 v 方法的第二个参数需要是 String 数据类型。因此,您需要将 InputStream iFile 转换为字符串。

    我引用了http://www.kodejava.org/examples/266.html

    您的 Activity 中需要以下导入:

    import java.io.IOException;
    import java.io.InputStream;
    import java.io.StringWriter;
    import java.io.Writer;
    import java.io.Reader;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    

    还有方法本身:

    public String convertStreamToString(InputStream is) throws IOException {
    
        /* To convert the InputStream to String we use the
        * Reader.read(char[] buffer) method. We iterate until the
        * Reader return -1 which means there's no more data to
        * read. We use the StringWriter class to produce the string.*/
        if (is != null) {
            Writer writer = new StringWriter();
            char[] buffer = new char[1024];
        try {
            Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        return writer.toString();
        } else {        
            return "";
        }
    
    }
    

    将您的 InputStream 传递到获取您的 String 和 Log.v 的方法中

    InputStream iFile = getResources().openRawResource(R.raw.textfile);
    String strInput = null;
    try {
      strInput = convertStreamToString(iFile);
    } catch (IOException e) {
      Log.v(TAG, "The string conversion failed.");
    }
    if(strInput != null){
      Log.v(TAG, strInput);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-31
      • 2012-01-17
      • 2021-11-06
      相关资源
      最近更新 更多