代码之家  ›  专栏  ›  技术社区  ›  Alin

Android读取文本原始资源文件

  •  105
  • Alin  · 技术社区  · 14 年前

    事情很简单,但并不像想象的那样。

    b) 如果适用法律要求对 软件,所有这些保证 自交货之日起天。

    (c) 无口头或书面信息或 其经销商、分销商、代理商或 员工应创建担保或 以任何方式增加任何

    (d) (仅限美国)有些州没有 允许排除隐含的 不适用于你。本保证提供 还有其他合法权利

    在我的屏幕上有这样一个布局:

    <LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
                         android:layout_width="fill_parent" 
                         android:layout_height="wrap_content" 
                         android:gravity="center" 
                         android:layout_weight="1.0"
                         android:layout_below="@+id/logoLayout"
                         android:background="@drawable/list_background"> 
    
                <ScrollView android:layout_width="fill_parent"
                            android:layout_height="fill_parent">
    
                        <TextView  android:id="@+id/txtRawResource" 
                                   android:layout_width="fill_parent" 
                                   android:layout_height="fill_parent"
                                   android:padding="3dip"/>
                </ScrollView>  
    
        </LinearLayout>
    

    读取原始资源的代码是:

    TextView txtRawResource= (TextView)findViewById(R.id.txtRawResource);
    
    txtDisclaimer.setText(Utils.readRawTextFile(ctx, R.raw.rawtextsample);
    
    public static String readRawTextFile(Context ctx, int resId)
    {
        InputStream inputStream = ctx.getResources().openRawResource(resId);
    
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    
        int i;
        try {
            i = inputStream.read();
            while (i != -1)
            {
                byteArrayOutputStream.write(i);
                i = inputStream.read();
            }
            inputStream.close();
        } catch (IOException e) {
            return null;
        }
        return byteArrayOutputStream.toString();
    }
    

    显示了文本get,但每行之后我都得到一个奇怪的字符[]如何删除该字符?我想是新线。

    工作溶液

    public static String readRawTextFile(Context ctx, int resId)
    {
        InputStream inputStream = ctx.getResources().openRawResource(resId);
    
        InputStreamReader inputreader = new InputStreamReader(inputStream);
        BufferedReader buffreader = new BufferedReader(inputreader);
        String line;
        StringBuilder text = new StringBuilder();
    
        try {
            while (( line = buffreader.readLine()) != null) {
                text.append(line);
                text.append('\n');
            }
        } catch (IOException e) {
            return null;
        }
        return text.toString();
    }
    
    10 回复  |  直到 11 年前
        1
  •  63
  •   nbro kai    6 年前

    如果使用基于字符的BufferedReader而不是基于字节的InputStream怎么办?

    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    String line = reader.readLine();
    while (line != null) { ... }
    

    别忘了 readLine() 跳过新行!

        2
  •  159
  •   Vovodroid    13 年前

    您可以使用:

        try {
            Resources res = getResources();
            InputStream in_s = res.openRawResource(R.raw.help);
    
            byte[] b = new byte[in_s.available()];
            in_s.read(b);
            txtHelp.setText(new String(b));
        } catch (Exception e) {
            // e.printStackTrace();
            txtHelp.setText("Error: can't show help.");
        }
    
        3
  •  28
  •   tbraun    9 年前

    如果使用apache“commons io”中的IOUtils,则更容易:

    InputStream is = getResources().openRawResource(R.raw.yourNewTextFile);
    String s = IOUtils.toString(is);
    IOUtils.closeQuietly(is); // don't forget to close your streams
    

    依赖项: http://mvnrepository.com/artifact/commons-io/commons-io

    马文:

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
    </dependency>
    

    等级:

    'commons-io:commons-io:2.4'
    
        4
  •  5
  •   Arsenius    5 年前

    有了Kotlin,你只需要一行代码就能做到:

    resources.openRawResource(R.raw.rawtextsample).bufferedReader().use { it.readText() }
    

    甚至声明扩展函数:

    fun Resources.getRawTextFile(@RawRes id: Int) =
            openRawResource(id).bufferedReader().use { it.readText() }
    

    val txtFile = resources.getRawTextFile(R.raw.rawtextsample)
    
        5
  •  3
  •   Shankar Narayana Damodaran    11 年前

    不如这样做:

    // reads resources regardless of their size
    public byte[] getResource(int id, Context context) throws IOException {
        Resources resources = context.getResources();
        InputStream is = resources.openRawResource(id);
    
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
    
        byte[] readBuffer = new byte[4 * 1024];
    
        try {
            int read;
            do {
                read = is.read(readBuffer, 0, readBuffer.length);
                if(read == -1) {
                    break;
                }
                bout.write(readBuffer, 0, read);
            } while(true);
    
            return bout.toByteArray();
        } finally {
            is.close();
        }
    }
    
        // reads a string resource
    public String getStringResource(int id, Charset encoding) throws IOException {
        return new String(getResource(id, getContext()), encoding);
    }
    
        // reads an UTF-8 string resource
    public String getStringResource(int id) throws IOException {
        return new String(getResource(id, getContext()), Charset.forName("UTF-8"));
    }
    

    从一个 ,添加

    public byte[] getResource(int id) throws IOException {
            return getResource(id, this);
    }
    

    测试用例 ,添加

    public byte[] getResource(int id) throws IOException {
            return getResource(id, getContext());
    }
    

    注意你的错误处理-当你的资源必须存在或某事是(非常?)时,不要捕捉和忽略异常。错了。

        6
  •  2
  •   borislemke    13 年前

    这是另一种方法,肯定能用,但我不能让它在一个活动中读取多个文本文件,在多个文本视图中查看,有人能帮忙吗?

    TextView helloTxt = (TextView)findViewById(R.id.yourTextView);
        helloTxt.setText(readTxt());
    }
    
    private String readTxt(){
    
     InputStream inputStream = getResources().openRawResource(R.raw.yourTextFile);
     ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    
     int i;
    try {
    i = inputStream.read();
    while (i != -1)
      {
       byteArrayOutputStream.write(i);
       i = inputStream.read();
      }
      inputStream.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
    e.printStackTrace();
    }
    
     return byteArrayOutputStream.toString();
    }
    
        7
  •  2
  •   Manish Sharma    12 年前

    @borislemke你也可以这样做

    TextView  tv ;
    findViewById(R.id.idOfTextView);
    tv.setText(readNewTxt());
    private String readNewTxt(){
    InputStream inputStream = getResources().openRawResource(R.raw.yourNewTextFile);
     ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    
     int i;
     try {
     i = inputStream.read();
    while (i != -1)
      {
       byteArrayOutputStream.write(i);
       i = inputStream.read();
       }
        inputStream.close();
      } catch (IOException e) {
       // TODO Auto-generated catch block
     e.printStackTrace();
     }
    
     return byteArrayOutputStream.toString();
     }
    
        8
  •  2
  •   alcsan    8 年前

    它比伏特加溶液更准确,比韦肯溶液更完整。

        try {
            InputStream inputStream = res.openRawResource(resId);
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                try {
                    StringBuilder result = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }
                    return result.toString();
                } finally {
                    reader.close();
                }
            } finally {
                inputStream.close();
            }
        } catch (IOException e) {
            // process exception
        }
    
        9
  •  1
  •   Massimiliano Kraus The Angry Programmer    8 年前

    1.首先创建一个目录文件夹并将其命名为res文件夹中的raw 3.在创建的.txt文件“articles.txt”中复制并粘贴所需的文本 4.不要忘记在main.xml中包含一个textview main活动.java

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gettingtoknowthe_os);
    
        TextView helloTxt = (TextView)findViewById(R.id.gettingtoknowos);
        helloTxt.setText(readTxt());
    
        ActionBar actionBar = getSupportActionBar();
        actionBar.hide();//to exclude the ActionBar
    }
    
    private String readTxt() {
    
        //getting the .txt file
        InputStream inputStream = getResources().openRawResource(R.raw.articles);
    
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    
        try {
            int i = inputStream.read();
            while (i != -1) {
                byteArrayOutputStream.write(i);
                i = inputStream.read();
            }
            inputStream.close();
    
        } catch (IOException e) {
            e.printStackTrace();
        }
        return byteArrayOutputStream.toString();
    }
    

        10
  •  1
  •   sakshi agrawal    7 年前
    InputStream is=getResources().openRawResource(R.raw.name);
    BufferedReader reader=new BufferedReader(new InputStreamReader(is));
    StringBuffer data=new StringBuffer();
    String line=reader.readLine();
    while(line!=null)
    {
    data.append(line+"\n");
    }
    tvDetails.seTtext(data.toString());
    
        11
  •  1
  •   ucMedia    6 年前

    这里有一个简单的方法来读取 未经加工的 文件夹:

    public static String readTextFile(Context context,@RawRes int id){
        InputStream inputStream = context.getResources().openRawResource(id);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    
        byte buffer[] = new byte[1024];
        int size;
        try {
            while ((size = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, size);
            }
            outputStream.close();
            inputStream.close();
        } catch (IOException e) {
    
        }
        return outputStream.toString();
    }
    
        12
  •  1
  •   semloh eh    5 年前

    这里是Kotlin中的一个实现

        try {
            val inputStream: InputStream = this.getResources().openRawResource(R.raw.**)
            val inputStreamReader = InputStreamReader(inputStream)
            val sb = StringBuilder()
            var line: String?
            val br = BufferedReader(inputStreamReader)
            line = br.readLine()
            while (line != null) {
                sb.append(line)
                line = br.readLine()
            }
            br.close()
    
            var content : String = sb.toString()
            Log.d(TAG, content)
        } catch (e:Exception){
            Log.d(TAG, e.toString())
        }