日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

android读取工程目录下的文件,Android编程实现读取工程中的txt文件功能

發(fā)布時間:2023/11/27 生活经验 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 android读取工程目录下的文件,Android编程实现读取工程中的txt文件功能 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

本文實例講述了Android編程實現(xiàn)讀取工程中的txt文件功能。分享給大家供大家參考,具體如下:

1. 眾所周知,Android的res文件夾是用來存儲資源的,可以在res文件夾下建立一個raw文件夾,放置在raw文件夾下的內(nèi)容會被原樣打包,而不會被編譯成二進制文件,并且可以通過R文件進行很方便地訪問。

比如我們可以將更新信息、版權(quán)信息等放到txt文件中,然后放到raw文件中,然后很方便地進行訪問。

在raw中放入一個a.txt文件,然后就可以在Activity中使用getResources().openRawResource(R.raw.a);方法獲取一個此文件的InputStream類,而后就可以很方便地進行讀寫a.txt了。

InputStream inputStream = getResources().openRawResource(R.raw.a);

一個獲取InputStream中字符串內(nèi)容的方法:

public static String getString(InputStream inputStream) {

InputStreamReader inputStreamReader = null;

try {

inputStreamReader = new InputStreamReader(inputStream, "gbk");

} catch (UnsupportedEncodingException e1) {

e1.printStackTrace();

}

BufferedReader reader = new BufferedReader(inputStreamReader);

StringBuffer sb = new StringBuffer("");

String line;

try {

while ((line = reader.readLine()) != null) {

sb.append(line);

sb.append("\n");

}

} catch (IOException e) {

e.printStackTrace();

}

return sb.toString();

}

傳入一個InputStream,返回其中的文本內(nèi)容。

其中:

inputStreamReader = new InputStreamReader(inputStream, "gbk");

為以gbk編碼讀取內(nèi)容,不同的文本文件可能編碼不同,如果出現(xiàn)亂碼,可能需要調(diào)整編碼

2. 下面通過一個例子講解讀取資源文件顯示在ScrollView當中:

①.ReadAsset.java文件:

package com.example.ReadAsset;

import android.app.Activity;

import android.os.Bundle;

import android.widget.TextView;

import java.io.IOException;

import java.io.InputStream;

public class ReadAsset extends Activity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.read_asset);

try {

//Return an AssetManager instance for your application's package

InputStream is = getAssets().open("index.txt");

int size = is.available();

// Read the entire asset into a local byte buffer.

byte[] buffer = new byte[size];

is.read(buffer);

is.close();

// Convert the buffer into a string.

String text = new String(buffer, "GB2312");

// Finally stick the string into the text view.

TextView tv = (TextView) findViewById(R.id.text);

tv.setText(text);

} catch (IOException e) {

// Should never happen!

throw new RuntimeException(e);

}

}

}

②. read_asset.xml文件

xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_height="fill_parent" android:paddingTop="50dip">

android:layout_height="wrap_content" android:textStyle="normal" />

③.然后在工程里面新建一個assets文件夾,隨便放一個index.txt的文件在其中,運行 Ctrl+F11進行測試即可;

希望本文所述對大家Android程序設計有所幫助。

總結(jié)

以上是生活随笔為你收集整理的android读取工程目录下的文件,Android编程实现读取工程中的txt文件功能的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。