码迷,mamicode.com
首页 > 其他好文 > 详细

andriod 资源文件之存取操作

时间:2016-03-05 23:27:05      阅读:271      评论:0      收藏:0      [点我收藏+]

标签:

来自:http://blog.csdn.net/jianghuiquan/article/details/8569235

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/read"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="读取资源文件(Raw)" />

    <TextView
        android:id="@+id/cont"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>
package com.example.yanlei.wifi;

import android.content.res.Resources;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
public class MainActivity extends AppCompatActivity {

    private Button btnRead=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnRead=(Button)super.findViewById(R.id.read);

        //读取资源文件
        btnRead.setOnClickListener(new OnClickListener(){
            public void onClick(View v)
            {
                //获取资源对象
                Resources res=MainActivity.this.getResources();
                //通过openRawResource()读取资源为R.raw.friend的资源文件,结果返回到InputStream
                InputStream input=res.openRawResource(R.raw.friend);
                //读取资源文件内容
                Scanner scan=new Scanner(input);
                StringBuffer info=new StringBuffer();
                while(scan.hasNext())
                    info.append(scan.next()).append("\n");
                scan.close();

                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                Toast.makeText(getApplicationContext(), info.toString(),Toast.LENGTH_LONG).show();
            }
        });

    }
}

我们把文件friend.txt保存到res/raw文件夹中。


  注意:raw文件不存在,需要你手动创建。

 

技术分享

andriod 资源文件之存取操作

标签:

原文地址:http://www.cnblogs.com/gisoracle/p/5246026.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!