80,351
社区成员
发帖
与我相关
我的任务
分享
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/tv1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/tv2"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
package lux.aust.android_sample_file2;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.util.EncodingUtils;
import android.app.Activity;
import android.content.res.Resources.NotFoundException;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class MainActivity extends Activity {
public static final String ENCODING = "UTF-8";
TextView tv1;
TextView tv2;
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById(R.id.tv1);
tv2 = (TextView) findViewById(R.id.tv2);
tv1.setText(getFromRaw("test1.txt"));
tv2.setText(getFromAsset("test2.txt"));
}
public String getFromAsset(String string) {
String result = "";
InputStream in = null;
try {
in = getResources().getAssets().open("test2.txt");
int length = in.available();
byte[] buffer = new byte[length];
in.read(buffer);
result = EncodingUtils.getString(buffer, ENCODING);
} catch (NotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
public String getFromRaw(String string) {
String result = "";
InputStream in = null;
try {
in = getResources().openRawResource(R.raw.test1);
int length = in.available();
byte[] buffer = new byte[length];
in.read(buffer);
result = EncodingUtils.getString(buffer, ENCODING);
} catch (NotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}