我有每秒生成数据并显示在屏幕上的代码。 这一切都工作正常,但我想创建所有数据的日志文件以便稍后分析。
每次创建数据时我都可以打开/写入/关闭文件,但我不确定它使用了多少处理能力,因为它不断打开和关闭文件
String data= reading1","+reading2+","+time +"/n";
try {
FileOutputStream out = openFileOutput("data.csv", Context.MODE_PRIVATE);
out.write(data.getBytes());
out.close();
} catch (Exception e) {
e.printStackTrace();
我希望在单击开始按钮时打开文件。
if ( v.getId() == R.id.start ){
// checks which button is clicked
Log.d("dennis", "Scan working"); //logs the text
// open a file
try {
FileOutputStream out = openFileOutput("data.csv", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
但是在关闭文件时,键入 out 时不会出现 .close() 选项
if ( v.getId() == R.id.stop ){
// checks which button is clicked
out. // no valid options appear
messageValue.setText(R.string.stopButtonText);// changes the hallo world text
readNoRead=false;
}
所有的打开/写入/关闭是否需要在一起或者是否可以
***open file***
-----
Cycle through all the data
-----
***Close file***
最佳答案
您应该在类的顶层存储指向 FileOutputStream
的链接。
您的代码示例:
FileOutputStream out;
void clickStart() {
if (v.getId() == R.id.start){
// checks which button is clicked
Log.d("dennis", "Scan working"); //logs the text
// open a file
try {
out = openFileOutput("data.csv", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
void writeData() {
String data= reading1+","+reading2+","+time +"/n";
try {
out.write(data.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
void clickStop() {
if (v.getId() == R.id.stop) {
try {
out.close();
} catch(IOException e) {
e.printStackTrace();
}
messageValue.setText(R.string.stopButtonText);// changes the hello world text
readNoRead=false;
}
}
关于java - Android studio,打开一个文件,不断写入然后关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60281375/