-
Notifications
You must be signed in to change notification settings - Fork 2
/
TextFileSaveLoad.java
50 lines (45 loc) · 1.78 KB
/
TextFileSaveLoad.java
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
import org.junit.Assert;
import org.junit.Test;
import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
public class TextFileSaveLoad extends Assert {
@Test
public void test() throws IOException {
int a[] = {2, 4, 35};
// Запись в текстовый файл
try (PrintWriter writer = new PrintWriter("text.txt")) {
writer.println("This is first string");
writer.println("A = 2");
writer.println(a.length);
for (int x : a) {
writer.println(x);
}
}
// Чтение из текстового файла
try (Scanner scanner = new Scanner(new File("text.txt"))) {
String firstLine = scanner.nextLine();
System.out.println("firstLine = " + firstLine);
String varName = scanner.next().trim();
String equals = scanner.next().trim();
int value = scanner.nextInt();
System.out.println("varName = \"" + varName + "\"");
System.out.println("equals = \"" + equals + "\"");
System.out.println("value = " + value);
// Считываем элементы массива
int arrayLength = scanner.nextInt();
int aNew[] = new int[arrayLength];
for (int i = 0; i < arrayLength; i++) {
aNew[i] = scanner.nextInt();
}
assertEquals(a.length, aNew.length);
assertArrayEquals(a, aNew);
}
try (FileReader fileReader = new FileReader("text.txt")) {
StreamTokenizer tokenizer = new StreamTokenizer(fileReader);
tokenizer.nextToken();
String value = tokenizer.sval;
System.out.println("value = " + value);
}
}
}