Android 读取文本原始资源文件

我添加了一个文本文件作为原始资源。该文本文件包含如下文本:

b) IF APPLICABLE LAW REQUIRES ANY WARRANTIES WITH RESPECT TO THE
SOFTWARE, ALL SUCH WARRANTIES ARE
LIMITED IN DURATION TO NINETY (90)
DAYS FROM THE DATE OF  DELIVERY.


(c) NO ORAL OR WRITTEN INFORMATION OR
ADVICE GIVEN BY  VIRTUAL ORIENTEERING,
ITS DEALERS, DISTRIBUTORS, AGENTS OR
EMPLOYEES SHALL CREATE A WARRANTY OR
IN ANY WAY INCREASE THE SCOPE OF ANY
WARRANTY PROVIDED HEREIN.


(d) (USA only) SOME STATES DO NOT
ALLOW THE EXCLUSION OF IMPLIED
WARRANTIES, SO THE ABOVE EXCLUSION MAY
NOT  APPLY TO YOU. THIS WARRANTY GIVES
YOU SPECIFIC LEGAL  RIGHTS AND YOU MAY
ALSO HAVE OTHER LEGAL RIGHTS THAT
VARY FROM STATE TO STATE.

在我的屏幕上有这样一个布局:

<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_weight="1.0"
android:layout_below="@+id/logoLayout"
android:background="@drawable/list_background">
            

<ScrollView android:layout_width="fill_parent"
android:layout_height="fill_parent">
                        

<TextView  android:id="@+id/txtRawResource"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="3dip"/>
</ScrollView>
   

</LinearLayout>

读取原始资源的代码是:

TextView txtRawResource= (TextView)findViewById(R.id.txtRawResource);


txtDisclaimer.setText(Utils.readRawTextFile(ctx, R.raw.rawtextsample);


public static String readRawTextFile(Context ctx, int resId)
{
InputStream inputStream = ctx.getResources().openRawResource(resId);


ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();


int i;
try {
i = inputStream.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
return null;
}
return byteArrayOutputStream.toString();
}

文本显示,但每行之后我得到奇怪的字符 []。如何删除字符?我觉得是新线路。

209182 次浏览

如果使用基于字符的 BufferedReader 而不是基于字节的 InputStream 会怎么样?

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = reader.readLine();
while (line != null) {
...
line = reader.readLine();
}

不要忘记 readLine()跳过了新的线路!

你可以用这个:

    try {
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.help);


byte[] b = new byte[in_s.available()];
in_s.read(b);
txtHelp.setText(new String(b));
} catch (Exception e) {
// e.printStackTrace();
txtHelp.setText("Error: can't show help.");
}

这是另一个方法,肯定会工作,但我不能让它读取多个文本文件查看在多个文本视图在一个单一的活动,任何人都可以帮助?

TextView helloTxt = (TextView)findViewById(R.id.yourTextView);
helloTxt.setText(readTxt());
}


private String readTxt(){


InputStream inputStream = getResources().openRawResource(R.raw.yourTextFile);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();


int i;
try {
i = inputStream.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


return byteArrayOutputStream.toString();
}

@ borislemke 你可以用类似的方法

TextView  tv ;
findViewById(R.id.idOfTextView);
tv.setText(readNewTxt());
private String readNewTxt(){
InputStream inputStream = getResources().openRawResource(R.raw.yourNewTextFile);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();


int i;
try {
i = inputStream.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


return byteArrayOutputStream.toString();
}

如果你使用来自 apache“ commons-io”的 IOUtils,那就更简单了:

InputStream is = getResources().openRawResource(R.raw.yourNewTextFile);
String s = IOUtils.toString(is);
IOUtils.closeQuietly(is); // don't forget to close your streams

依赖关系: http://mvnrepository.com/artifact/commons-io/commons-io

美芬:

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>

格拉德尔:

'commons-io:commons-io:2.4'

不如这样做:

// reads resources regardless of their size
public byte[] getResource(int id, Context context) throws IOException {
Resources resources = context.getResources();
InputStream is = resources.openRawResource(id);


ByteArrayOutputStream bout = new ByteArrayOutputStream();


byte[] readBuffer = new byte[4 * 1024];


try {
int read;
do {
read = is.read(readBuffer, 0, readBuffer.length);
if(read == -1) {
break;
}
bout.write(readBuffer, 0, read);
} while(true);


return bout.toByteArray();
} finally {
is.close();
}
}


// reads a string resource
public String getStringResource(int id, Charset encoding) throws IOException {
return new String(getResource(id, getContext()), encoding);
}


// reads an UTF-8 string resource
public String getStringResource(int id) throws IOException {
return new String(getResource(id, getContext()), Charset.forName("UTF-8"));
}

活动加上

public byte[] getResource(int id) throws IOException {
return getResource(id, this);
}

或从 测试案例,添加

public byte[] getResource(int id) throws IOException {
return getResource(id, getContext());
}

注意你的错误处理-不要捕获和忽略异常时,你的资源必须存在或东西(非常?)错了。

1. 首先创建一个 Directory 文件夹,并在 res 文件夹中将其命名为 raw 2. 在前面创建的原始目录文件夹中创建一个. txt 文件,并将其命名为 eg.articles.txt... 。 3. 复制并粘贴您想要的文本到您创建的“ articles.txt”文件的. txt 文件中 4. 不要忘记在 main.xml 中包含一个 textview MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gettingtoknowthe_os);


TextView helloTxt = (TextView)findViewById(R.id.gettingtoknowos);
helloTxt.setText(readTxt());


ActionBar actionBar = getSupportActionBar();
actionBar.hide();//to exclude the ActionBar
}


private String readTxt() {


//getting the .txt file
InputStream inputStream = getResources().openRawResource(R.raw.articles);


ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();


try {
int i = inputStream.read();
while (i != -1) {
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();


} catch (IOException e) {
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}

希望有用!

这是周末和 Vovodroid 的混合解决方案。

它比 Vovodroid 的解决方案更正确,比周末的解决方案更完整。

    try {
InputStream inputStream = res.openRawResource(resId);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
return result.toString();
} finally {
reader.close();
}
} finally {
inputStream.close();
}
} catch (IOException e) {
// process exception
}
InputStream is=getResources().openRawResource(R.raw.name);
BufferedReader reader=new BufferedReader(new InputStreamReader(is));
StringBuffer data=new StringBuffer();
String line=reader.readLine();
while(line!=null)
{
data.append(line+"\n");
}
tvDetails.seTtext(data.toString());

这里有一个从 生的文件夹读取 文本文件的简单方法:

public static String readTextFile(Context context,@RawRes int id){
InputStream inputStream = context.getResources().openRawResource(id);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte buffer[] = new byte[1024];
int size;
try {
while ((size = inputStream.read(buffer)) != -1)
outputStream.write(buffer, 0, size);
outputStream.close();
inputStream.close();
} catch (IOException e) {


}
return outputStream.toString();
}

下面是 Kotlin 的一个实现

    try {
val inputStream: InputStream = this.getResources().openRawResource(R.raw.**)
val inputStreamReader = InputStreamReader(inputStream)
val sb = StringBuilder()
var line: String?
val br = BufferedReader(inputStreamReader)
line = br.readLine()
while (line != null) {
sb.append(line)
line = br.readLine()
}
br.close()


var content : String = sb.toString()
Log.d(TAG, content)
} catch (e:Exception){
Log.d(TAG, e.toString())
}

对于 Kotlin,你只需要一行代码就可以做到:

resources.openRawResource(R.raw.rawtextsample).bufferedReader().use { it.readText() }

甚至声明扩展函数:

fun Resources.getRawTextFile(@RawRes id: Int) =
openRawResource(id).bufferedReader().use { it.readText() }

然后直接使用它:

val txtFile = resources.getRawTextFile(R.raw.rawtextsample)

这里有一句话:

String text = new BufferedReader(
new InputStreamReader(getResources().openRawResource(R.raw.my_file)))
.lines().reduce("\n", (a,b) -> a+b);
val inputStream: InputStream = resources.openRawResource(R.raw.product_json)
val reader: Reader = BufferedReader(InputStreamReader(inputStream, "utf-8"))


val writer: Writer = StringWriter()
val buffer = CharArray(1024)
reader.use { it ->
var n: Int
while (it.read(buffer).also { n = it } != -1) {
writer.write(buffer, 0, n)
}
}
val stringVal = writer.toString()