[英]Android studio, open a file , continuously write and then close
我有每秒生成數據並顯示在屏幕上的代碼。 這一切正常,但我想創建所有數據的日志文件以供稍后分析。
每次創建數據時我都可以打開/寫入/關閉文件,但我不確定這使用了多少處理能力,因為它不斷打開和關閉文件
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***
絕對可以在一個塊中打開、處理和關閉文件而不關閉文件。
您的out
變量未顯示任何方法建議,因為它尚未在該塊中定義。 換線
FileOutputStream out = openFileOutput("data.csv", CONTEXT.MODE_PRIVATE);
到
out = openFileOutput("data.csv", CONTEXT.MODE_PRIVATE);
然后將FileOutputStream out;
添加FileOutputStream out;
到第一個if
語句上方的一行(塊外)。
您可能還想查看 'try-catch-finally' 或 'try with resources' 作為關閉 try-catch 塊中文件的選項。
您應該在類的頂層存儲指向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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.