該應用程序會記錄傳感器數據並將數據寫入.txt文件中並存入手機SD卡。無法將最後一行寫入.txt文件 - Android
在數據收集過程中,可以隨時按停止按鈕停止寫入。
一旦停止按鈕被按下,我想追加「文件結束」,然後關閉它。
但我從來沒有看到在最後出現的字符串。哪裏出錯?
停止按鈕部分:
// stop button
stopButton = (Button) findViewById(R.id.button6);
stopButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startFlag = false;
// record down the step count both in file and UI
listAdapter.add(txtName.getText() + ".txt: " + String.valueOf(stepCount));
dataCollector.myPrintWriter.write("End Of File");
dataCollector.clearStampNumber();
dataCollector.stopSaving();
}
});
文件寫作部分:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import android.widget.CheckBox;
import android.widget.EditText;
public class DataCollector {
File myFile;
FileOutputStream fOut;
OutputStreamWriter myOutWriter;
BufferedWriter myBufferedWriter;
PrintWriter myPrintWriter;
private boolean isStamped;
private int timeStampNo;
// constructor
public DataCollector() {
isStamped = false;
timeStampNo = 0;
accelerationWanted = false;
rotationRateWanted = false;
magneticFieldWanted = false;
}
public void setStamp() {
isStamped = true;
timeStampNo++;
}
public void setFilePath(EditText txtName) {
myFile = new File("/sdcard/ResearchData/" + txtName.getText() + ".txt");
try {
myFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut = new FileOutputStream(myFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
myOutWriter = new OutputStreamWriter(fOut);
myBufferedWriter = new BufferedWriter(myOutWriter);
myPrintWriter = new PrintWriter(myBufferedWriter);
}
public void saveData(double[] acceleration, double[] rotationRate, double[] magneticField, long startTime, long currentTime) {
myPrintWriter.write(currentTime - startTime + " " + acceleration[0] + " " + acceleration[1] + " " + acceleration[2] + " " + rotationRate[0] + " " + rotationRate[1] + " " + rotationRate[2] + " " + magneticField[0] + " " + magneticField[1] + " " + magneticField[2] + "\n");
}
public void stopSaving() {
myPrintWriter.flush();
myPrintWriter.close();
try {
myOutWriter.close();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
你如何驗證該文件不包含最後一行?是否可能需要在行尾添加\ n? – njzk2
@ njzk2我通過查找字符串「End Of File」來驗證它是否包含最後一行。 txt文件中根本沒有這樣的字符串... –
你可以發佈驗證碼,只是爲了安全起見嗎? – njzk2