qq_38813780
清水鼻涕泡
2017-10-24 13:28

安卓读取TXT文件转为float数组

1
  • 编码
  • android
  • arraylist
  • textview

package com.example.asus.arraytest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
private TextView tv;
private float[] array;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv= (TextView) findViewById(R.id.tv);
array=createArray("E:\data3.txt");
String sum="";
for(int i=0;i<array.length;i++){
sum=sum+array[i];
}
tv.setText(sum);
}

public List readTxt(String filePath) {
    int cout = 0;// 读取行数
    String encoding = "UTF-8";//设置编码
    File file = new File(filePath);
    BufferedReader bufferedReader = null;
    ArrayList<Float> list = new ArrayList<>();
    try {
        InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
        bufferedReader = new BufferedReader(read);
        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            String[] s = str.split("\n|\r");//根据文件中的格式来,可能是空格,逗号之类的。
            for (int i = 0; i < s.length; i++)
                list.add(Float.valueOf(s[i]));
            cout++;
            //貌似toast很费时,所以这边注释掉了
            //Toast.makeText(MainActivity.this,"读取中ing.....",Toast.LENGTH_SHORT).show();
        }
        bufferedReader.close();
        read.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    Toast.makeText(MainActivity.this, "read  over .", Toast.LENGTH_SHORT).show();
    return list;
}

public float[] createArray(String filePath) {

    List list = readTxt(filePath);
    int size=list.size();
    float[] array = new float[size];
    for(int i=0;i<size;i++){
        array[i]= (float)list.get(i);
    }

    return array;
}

}
代码如上 请问为什么一直都不出文件呢 直接显示READOVER 用的绝对路径错了吗

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

3条回答

为你推荐