-
Notifications
You must be signed in to change notification settings - Fork 1
/
Reading and Writing
68 lines (62 loc) · 2.06 KB
/
Reading and Writing
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package com.example.student.coords;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
public class MainActivity extends AppCompatActivity {
final String LOG_TAG = "myLogs";
final String FILENAME = "MyFile123";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
public void onclick(View v) {
writeFile();
readFile();
}
void writeFile() {
try {
// отрываем поток для записи
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
openFileOutput(FILENAME, MODE_PRIVATE)));
// пишем данные
bw.write("Содержимое файла");
// закрываем поток
bw.close();
Log.d(LOG_TAG, "Файл записан");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
void readFile() {
try {
// открываем поток для чтения
BufferedReader br = new BufferedReader(new InputStreamReader(
openFileInput(FILENAME)));
String str = "";
// читаем содержимое
while ((str = br.readLine()) != null) {
Log.d(LOG_TAG, str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}