一、写一个NodeLocation类
它的的功能是读出txt文件,要求txt文件中内容规范为以下格式:
要隔开的信息用英文逗号分隔,而且每一行的信息结束后要换行。
该类的代码如下:
public class NodeLocation {
static ArrayList<String> nodes = new ArrayList<>();
private static int iNum=0;
private static String[] split = new String[2];
public static ArrayList<String> txt2String(File file){
try {
//构造一个BufferedReader类来读取文件
BufferedReader br = new BufferedReader(new FileReader(file));
String s = null;
//使用readLine方法,一次读一行,txt中的值分别是经度、纬度
while ((s = br.readLine()) != null) {
split = s.split(",");//每一行的两个值通过“,”来分割开,并存放到数组中
nodes.add(split[0]);//将String型数组splite的信息添加到nodes中
nodes.add(split[1]);
iNum= iNum +2;
}
br.close();//要求读完信息之后要手动将BufferReader关闭
} catch (Exception e) {
e.printStackTrace();
}
return nodes;
}
二、调用该类
Nodes = NodeLocation.txt2String(new File(Environment.
getExternalStorageDirectory() + "/Position.txt"));
//将要用的文件放在根目录下,取名为Position.txt
//调用NodeLocation的txt2String方法,该方法返回一个ArrayList类型的数组
三、其他须知
因为在定义txt2String的时候是String型的数组链表,所以我们在这里需要把String类型转化为Double类型,从而才能进行后续的计算,调用方法如下:
double c = Double.parseDouble(Nodes.get(0));
//Nodes.get(0)是一个String类型的字符串,如果我们想将其变为Double型浮点数,
//只需调用Double.parseDouble()方法,想要变成int,则需用Integer.parseInt方法
小tips:
int d = Integer.parseInt(Nodes.get(0));
//这个会报错,因为Nodes.get(0)="116.915872"
//这个数本来就不是int型,不能用该方法直接变为int
int d = (int)Double.parseDouble(Nodes.get(0));
//可以加一个类型强转符,这样可以成功运行