Я сомневаюсь в своем коде. Я создаю приложение java, в котором оно проверяет, существует ли файл json, и если он существует, он будет обновлен (в противном случае он будет создан и отредактирован). Он будет обновлен с помощью моего класса пользователя
класса пользователя:
public class User {
//user's variables
String name;
String second_name;
int age;
String email;
String user_id; //automatically generated
String password;
//constructor without parameters
public User() {}
//coonstructor with parameters
public User(String name, String second_name, int age, String email, String user_id, String password) {
this.name = name;
this.second_name = second_name;
this.age = age;
this.email = email;
this.user_id = user_id;
this.password = password;
}
//Setters and getters
public void setName(String name) {
this.name = name;
}
public void setSecond_name(String second_name) {
this.second_name = second_name;
}
public void setAge(int age) {
this.age = age;
}
public void setEmail(String email) {
this.email = email;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public String getSecond_name() {
return second_name;
}
public int getAge() {
return age;
}
public String getEmail() {
return email;
}
public String getUser_id() {
return user_id;
}
public String getPassword() {
return password;
}
////////////////////////////////////////////////////////////////////////////////////////////////
//FUNCTIONS
public String toString(){
String personal_data =
"Id:"+this.getUser_id()+
"\nEmail:"+this.getEmail()+
"\nPassword: "+this.getPassword()+
"\nName: "+this.getName()+
"\nSecond name: "+this.getSecond_name()+
"\nAge: "+this.getAge();
return personal_data;
}
////////////////////////////////////////////////////////////////////////////////////////////////
}
И моего основного класса, в котором я обновляю свой json файл:
import com.google.gson.Gson;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.*;
public class main {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
//menu
System.out.println("Welcome to Vault's App.");
System.out.println("================================");
System.out.println("Please, choose an option:");
System.out.println("1.Sign up");//Sign up
System.out.println("2.Log in");//Log in
System.out.println("3.View Security's Log");//View Security's Log
System.out.println("4.Print data");
int option = scanner.nextInt();
menu(option);
}
public static void menu(int opt) throws IOException {
switch (opt){
case 1:
signUp(); //sign up function
break;
case 2:
logIn();//log in function
break;
case 3:
securityLog();//security log (check password and python script[root access])
break;
case 4:
printData();//print hashmap
break;
}
}
public static void signUp() throws IOException {// add user
String path = "E:\\1PROGRAMMING\\AccountsGestor\\src\\users.json";
User new_user = new User();//new user's instance
Scanner scanner = new Scanner(System.in);
System.out.println("Enter data: ");
System.out.println("==================");
String id = generateUserId() ;
System.out.println("Enter your email: ");
String emailUser = scanner.nextLine();
System.out.println("Enter your password: ");
String passwordUser = ingressPassword();
System.out.println("Enter your name: ");
String nameUser = scanner.nextLine();
System.out.println("Enter your second name: ");
String second_name_User = scanner.nextLine();
System.out.println("Enter your age: ");
int ageUser = scanner.nextInt();
new_user.setUser_id(id);
new_user.setEmail(emailUser);
new_user.setPassword(passwordUser);
new_user.setName(nameUser);
new_user.setSecond_name(second_name_User);
new_user.setAge(ageUser);
//Test
//System.out.println(new_user.toString());
//json array
ArrayList<User> allItems = new ArrayList<>();
Writer writer = new FileWriter(path);
File temp = new File(path);
try
{
temp.createTempFile("users", ".json");
boolean exists = temp.exists();
if (!exists){
System.out.println("No json file detected. Creating...");
new Gson().toJson(jsonArray(allItems,new_user,path),writer);
writer.close();
}else{
System.out.println("Temp file exists ");
//read json data
//add allItems element
}
} catch (IOException e)
{
e.printStackTrace();
}
}
public static ArrayList jsonArray(ArrayList allItems, User user, String path) throws IOException {
//adding arraylist new element
allItems.add(new User(user.getName(),user.getSecond_name(),user.getAge(),user.getEmail(),user.getUser_id(),user.getPassword()));
return allItems;
}
public static void logIn(){System.out.println("PENDING");}
public static void securityLog(){//check passwords saved (root)
System.out.println("PENDING");
}
public static void printData() {
System.out.println("PENDING");
}
public static String generateUserId(){
int MAX = 20;
String elements = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuilder idGenerated = new StringBuilder(MAX);
for (int i =0 ;i < MAX; i++){
int randomInt = random.nextInt(elements.length());
idGenerated.append(elements.charAt(randomInt));
}
return idGenerated.toString();
}
public static String ingressPassword(){//CALLING TO PYTHON SCRIPT PASSWORDCHECKER
Scanner scanner = new Scanner(System.in);
String psswd = scanner.nextLine();
//export info from python
return (psswd);
}
}
Я могу создавать и помещать новые данные, но мне нужно знать, как я могу обновить файл json, если он существует.