在Android Studio中读取数字文本文件并将每个数字放在数组索引中

时间:2016-01-25 21:51:18

标签: java android-studio

我有一个这样的文本文件:p102_triangles.txt,其中包含如下数据:

-340,495,-153,-910,835,-947

-175,41,-421,-714,574,-645

-547,712,-352,579,951,-786

419,-864,-83,650,-399,171

-429,-89,-357,-930,296,-29

-734,-702,823,-745,-684,-62

-971,762,925,-776,-663,-157

...

我想在Android Studio中读取此txt文件,并将每个数字放在整数数组索引中。

这是我的java文件:

package com.example.davinci.trianglecontainment;

import android.app.Activity;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class triangleContainment extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.triangle_containment_layout);
    }

}

这是应用程序中的文件夹树:

enter image description here

1 个答案:

答案 0 :(得分:1)

您基本上需要将文本文件读入String,然后按换行符和逗号分隔字符串。这是一种方法:

private static String readTextFileFromAssets(Context context, String fileName){
    String ret = "";
    final android.content.res.AssetManager am = context.getResources().getAssets();
    java.io.InputStream is = null;
    try{
        is = am.open(fileName);

        if(is != null){
            java.io.BufferedReader r = new java.io.BufferedReader(new java.io.InputStreamReader(is), 8000);
            StringBuilder total = new StringBuilder();
            String line;
            while ((line = r.readLine()) != null) {
                total.append(line);
            }
            ret = total.toString();
        }


    }catch(Exception e){
        //handle error reading text file here
    }

    //return
    return ret;

}

private static java.util.ArrayList<Integer> readFileIntoArray (Context context) {
    String file = readTextFileFromAssets(context, "p102_triangles.txt");
    java.util.ArrayList<Integer> ret = new java.util.ArrayList<>();
    String[] lines = file.split("\n");
    for (String line : lines) {
        String[] values = line.split(",");
        for (String value : values) ret.add(Integer.parseInt(value));
    }
    return ret;
}