一個用JAVA解析TXT格式文字文件的程式舉例
阿新 • • 發佈:2019-01-11
實體類
package txt;
public class AliDataRecord {
private String FSTR_SCATSID;
private String FSTR_DESC;
private String FSTR_DATE;
private String NUM_TIME;
private String MIN_TIME;
private String NUMOF_ALARMS;
private String UTIM;
public String getFSTR_SCATSID () {
return FSTR_SCATSID;
}
public void setFSTR_SCATSID(String fSTR_SCATSID) {
FSTR_SCATSID = fSTR_SCATSID;
}
public String getFSTR_DESC() {
return FSTR_DESC;
}
public void setFSTR_DESC(String fSTR_DESC) {
FSTR_DESC = fSTR_DESC;
}
public String getFSTR_DATE() {
return FSTR_DATE;
}
public void setFSTR_DATE(String fSTR_DATE) {
FSTR_DATE = fSTR_DATE;
}
public String getNUM_TIME() {
return NUM_TIME;
}
public void setNUM_TIME(String nUM_TIME) {
NUM_TIME = nUM_TIME;
}
public String getMIN_TIME() {
return MIN_TIME;
}
public void setMIN_TIME(String mIN_TIME) {
MIN_TIME = mIN_TIME;
}
public String getNUMOF_ALARMS() {
return NUMOF_ALARMS;
}
public void setNUMOF_ALARMS(String nUMOF_ALARMS) {
NUMOF_ALARMS = nUMOF_ALARMS;
}
public String getUTIM() {
return UTIM;
}
public void setUTIM(String uTIM) {
UTIM = uTIM;
}
@Override
public String toString() {
return "AliDataRecord [FSTR_SCATSID=" + FSTR_SCATSID + ", FSTR_DESC="
+ FSTR_DESC + ", FSTR_DATE=" + FSTR_DATE + ", NUM_TIME="
+ NUM_TIME + ", MIN_TIME=" + MIN_TIME + ", NUMOF_ALARMS="
+ NUMOF_ALARMS + ", UTIM=" + UTIM + "]";
}
}// 實體類的建立與輸出結果的列印 重寫toString類
如何修改編碼格式
解析類
package txt;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class Txt {
public static void readTxt(String filePath) {
List<AliDataRecord> records = new ArrayList<AliDataRecord>();// 建立list
// 將txt格式的資料存入陣列
try {
File file = new File(filePath);
if (file.isFile() && file.exists()) {
InputStreamReader isr = new InputStreamReader(
new FileInputStream(file), "utf-8");
BufferedReader br = new BufferedReader(isr);
String lineTxt = null; // 讀取檔案的方法
while ((lineTxt = br.readLine()) != null) {
String[] arrStrings = lineTxt.split(","); // 用於把一個字串分割成字串陣列
AliDataRecord record = new AliDataRecord();
record.setFSTR_SCATSID(arrStrings[0]);
record.setFSTR_DESC(arrStrings[1]);
record.setFSTR_DATE(arrStrings[2]);
record.setNUM_TIME(arrStrings[3]);
record.setMIN_TIME(arrStrings[4]);
record.setNUMOF_ALARMS(arrStrings[5]);
record.setUTIM(arrStrings[6]);
records.add(record); // 用set方法將取值分別新增到對應字串陣列 ,用add方法存入list
}
br.close();
for (int i = 0; i < records.size(); i++) {
System.out.println(records.get(i));
}
} else {
System.out.println("檔案不存在!");
}
} catch (Exception e) {
System.out.println("檔案讀取錯誤!");
}
}
public static void main(String[] args) {
String filePath = "D:\\Work\\myeclipse\\B\\txt\\src\\aaaaa.txt"; // 讀取檔案的絕對路徑
readTxt(filePath);
}
}
add方法和set方法的區別
add方法是在某個指定的位置加上某個物件,並將原來的位置的那個物件向後擠了一格。
set方法是將原來位置上的那個給取代了,並將原來位置上物件的返回。
執行結果