您的位置:首页 > 移动开发 > Android开发

android assets文件夹应用

2012-07-17 22:34 162 查看
Android 系统为每个新设计的程序提供了/assets目录,这个目录保存的文件可以打包在程序里。/res 和/assets的不同点是,android不为/assets下的文件生成ID。如果使用/assets下的文件,需要指定文件的路径和文件名。下面这个例子,显示如何访问/assets下的内容。

在文件中/assets 中建立/image子目录,将/res/drawable下的icon.png子目录拷贝到该目录中。在/assets目录中建立readme.txt文件,文件中输入文本“hello,xiao Yiwei!”。




[/img]

Java代码



public class MainActivity extends Activity {

private EditText firstField;

private EditText secondField;



@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);



firstField = (EditText) findViewById(R.id.firstId);

secondField = (EditText) findViewById(R.id.secondId);



AssetManager assetManager = getAssets();

try {

String[] files = assetManager.list("image");

firstField.setText(Integer.toString(files.length)

+ "file.File name is" + files[0]);

InputStream inputStream = assetManager.open("readme.txt");

String s = readTextFile(inputStream);

secondField.setText(s);



} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}



private String readTextFile(InputStream inputStream) {

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

byte buf[] = new byte[1024];

int len;

try {

while ((len = inputStream.read(buf)) != -1) {

outputStream.write(buf, 0, len);

}

outputStream.close();

inputStream.close();

} catch (IOException e) {

}

return outputStream.toString();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: