-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTextFileToJSONFile.java
More file actions
45 lines (40 loc) · 1.32 KB
/
TextFileToJSONFile.java
File metadata and controls
45 lines (40 loc) · 1.32 KB
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
package module10;
import java.io.*;
import java.util.*;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
public class TextFileToJSONFile {
public static void main(String[] args) throws IOException {
HashMap<String, String> hashMap = new HashMap<>();
String[] words = new String[0];
try (BufferedReader br = new BufferedReader
(new FileReader("/Users/mac/Desktop/Java/Module10/src/file2.txt"))) {
br.readLine(); // <-- skipping first line
String line = br.readLine();
while (line != null) {
words = line.split(" ");
hashMap.put(words[0], words[1]);
line = br.readLine();
}
}
User user = new User(words[0], words[1]);
ArrayList users = new ArrayList();
for (int i = 0; i<hashMap.size(); i++){
users.add(user);
}
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(users);
System.out.println(json);
}
}
class User {
private String name;
private String age;
public User(String name, String age) {
this.name = name;
this.age = age;
}
}