Skip to content

Instantly share code, notes, and snippets.

@edward1986
Created December 2, 2020 09:13
Show Gist options
  • Save edward1986/a9dfbc05cdd95bf43d33305801f6d7c6 to your computer and use it in GitHub Desktop.
Save edward1986/a9dfbc05cdd95bf43d33305801f6d7c6 to your computer and use it in GitHub Desktop.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView android:id="@+id/textViewRaw"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center_horizontal|center_vertical"
tools:ignore="MissingConstraints" />
<TextView android:id="@+id/textViewAsset"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
package com.example.readingresourcefiles;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textViewRaw = findViewById(R.id.textViewRaw);
textViewRaw.setText(getText(this.getResources().openRawResource(R.raw.raw_text)));
TextView textViewAsset = findViewById(R.id.textViewAsset);
try {
textViewAsset.setText(getText(this.getAssets().open("asset_text.txt")));
} catch (IOException e) {
e.printStackTrace();
}
}
private String getText(InputStream inputStream) {
StringBuilder stringBuilder = new StringBuilder();
try {
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String newLine = null;
while ((newLine = bufferedReader.readLine()) != null) {
stringBuilder.append(newLine + "\n");
}
inputStream.close();
}
} catch (java.io.IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment