日期:2014-05-20  浏览次数:20783 次

java 讀取txt 問題
我在c:\gps.txt   內容如下

$GPRMC,055148,A,2407.8945,N,12041.7649,E,000.0,000.0,061196,003.1,W*69
$GPRMC,055328,A,2337.8945,N,12434.7649,E,230.0,020.0,062396,003.1,W*12
................
...........
$GPRMC,052148,A,2887.8945,w,12041.7649,E,000.0,110.0,061196,111.1,W*45

如何可以做到一行一行地讀?
然後可以把第一個逗號與第二個逗號之間數值放在gpsarray[0][0]中
第二個逗號與第三個逗號之間數值放在gpsarray[0][1]中
第三個逗號與第四個逗號之間數值放在gpsarray[0][2]中
如此類推..
但這樣如果數據量很多,會不會效能極低?
用java   fileinputstream又如何做到
希望有詳細程序,謝謝各位了!!!

------解决方案--------------------
Scanner in = new Scaner(new FileInputStream(new File( "C:\\gps.txt ");
while(in.hasNextLine())
{
String str = in.nextLine();
gpsarray[i] = str.split( ", ")
i++;
}
徒手写的,应该没问题
------解决方案--------------------
gpsarray[i] 最好还是换用list
------解决方案--------------------
这样设计的效率很低,你可以根据一行数据的格式设计一个类,将一行的数据都存在该类里。

如果是固定的行数,就建一个数组,如果不固定的行数,就建一个集合,用来存储。

一行一行读的代码如下

BufferedReader br;
try {
br = new BufferedReader(new FileReader( "c:\\gps.txt "));
String[][] gpsdate = new String[10][10];
int i = 0;
String s = null;
do {
s = br.readLine();
String[] sa = s.split( ", ");
for(int j=0;j <sa.length;j++){
gpsdate[i][j] = sa[j];
}
} while (s != null);
} catch (Exception e) {
e.printStackTrace();
}
------解决方案--------------------

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;

public class Test2 {
public static void main(String[] args) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader( "c:\\gps.txt "));
String s = null;
ArrayList list = new ArrayList();
while ((s = br.readLine()) != null) {
list.add(s.split( ", "));
}
String[][] gpsdate = new String[list.size()][];
for (int i = 0; i < list.size(); i++) {
gpsdate[i] = (String[]) list.get(i);
}
for(int j = 0; j < gpsdate.length; j++) {
for(int m = 0; m < gpsdate[j].length; m++) {
System.out.print( "gpsdate[ "+j+ "][ "+m+ "] = " + gpsdate[j][m] + "\t ");
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}

随便写了个,你看一下
------解决方案--------------------
while(in.hasNextLine())
{
String str = in.nextLine();
}