应用程序记录传感器数据并将数据写入.txt文件到手机SD卡中。
在数据收集过程中,可以随时按停止按钮停止写入。
相关的写作部分如下:
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;
boolean accelerationWanted;
boolean rotationRateWanted;
boolean magneticFieldWanted;
// 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() {
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();
}
}
}
无论我调用saveData()和stopSaving()的顺序如何,最后一行总是不完整的。在右边,我在主要活动中执行以下操作:
dataCollector.saveData();
dataCollector.stopSaving();
我先保存数据,然后停止保存。为什么最后一行仍然不完整?
知道如何解决这个问题吗?要么完成最后一行,要么丢弃它就可以了。
提前致谢!
答案 0 :(得分:0)
在关闭前尝试使用flush:
public void stopSaving() {
try {
myPrintWriter.flush();
myPrintWriter.close();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
try {
myOutWriter.flush();
myOutWriter.close();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
try {
fOut.flush();
fOut.close();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
答案 1 :(得分:0)
你应该在关闭之前刷新你的编写器对象。
如下所示:
myOutWriter.flush();
myOutWriter.close();
和
fOut.flush();
fOut.close();