Dernière fois, version Java de l'outil simple "Key Value Store Saved in Local JSON File" écrit en Golang. En tant que produit en série, j'ai initialement écrit et comparé des programmes avec le même contenu dans plusieurs langues "Apprenez en comparant chaque langage de programmation grâce à la création d'un outil simple" Version améliorée de.
--Partie 1: Apprenez en comparant chaque langage de programmation grâce à la création d'outils simples
$ java -version
openjdk version "1.8.0_202"
OpenJDK Runtime Environment (build 1.8.0_202-20190206132807.buildslave.jdk8u-src-tar--b08)
OpenJDK GraalVM CE 1.0.0-rc14 (build 25.202-b08-jvmci-0.56, mixed mode)
IntelliJ IDEA 2019.2 (Ultimate Edition)
Build #IU-192.5728.98, built on July 23, 2019
Une application console qui a la capacité d'enregistrer des informations textuelles dans un fichier JSON au format clé-valeur lorsque l'application est lancée. Les spécifications sont les mêmes que dans la partie 1, sauf qu'elles ont été conservées en mémoire, donc voir ci-dessous pour plus de détails. https://qiita.com/sky0621/items/32c87aed41cb1c3c67ff#要件
https://github.com/sky0621/book_java/tree/v0.2.0
Source Java | La description |
---|---|
Main.java | Point d'entrée du lancement de l'application |
StoreInfo.java | Stocker pour stocker les informations de valeur-clé(Fichier JSON)Gère les informations sur. Actuellement, seul le "nom de fichier" est conservé |
Commands.java | Gérez chaque commande, comme l'acquisition, l'enregistrement et la suppression des informations du magasin de valeurs de clé. Les effets des commandes croissantes ou décroissantes sont fermés à cette source. |
Command.java | Interface commune pour chaque commande |
SaveCommand.java | Responsable du stockage des informations de valeur clé. |
GetCommand.java | Responsable de l'acquisition de la valeur de la clé spécifiée. |
ListCommand.java | Responsable de l'acquisition de toutes les informations de valeur clé. |
RemoveCommand.java | Responsable de la suppression de la valeur de la clé spécifiée. |
ClearCommand.java | Responsable de la suppression de toutes les informations de valeur clé. |
HelpCommand.java | Responsable de l'affichage des informations d'aide. |
EndCommand.java | Responsable de la résiliation de l'application. |
[Main.java]
import java.util.Scanner;
public class Main {
public static void main(String... args) {
Commands commands = new Commands(new StoreInfo("store.json"));
System.out.println("Start!");
while (true) {
Scanner s = new Scanner(System.in);
String cmd = s.nextLine();
commands.exec(cmd.split(" "));
}
}
}
[StoreInfo.java]
import org.apache.commons.lang3.StringUtils;
public class StoreInfo {
private static final String DEFAULT_STORE_NAME = "store.json";
private String storeName;
public StoreInfo(String storeName) {
if (StringUtils.isEmpty(storeName)) {
this.storeName = DEFAULT_STORE_NAME;
} else {
this.storeName = storeName;
}
}
public String getName() {
return this.storeName;
}
}
[Commands.java]
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Commands {
private Map<String, Command> commands;
public Commands(StoreInfo storeInfo) {
commands = new HashMap<>();
commands.put("end", new EndCommand());
commands.put("help", new HelpCommand());
commands.put("clear", new ClearCommand(storeInfo));
commands.put("save", new SaveCommand(storeInfo));
commands.put("get", new GetCommand(storeInfo));
commands.put("remove", new RemoveCommand(storeInfo));
commands.put("list", new ListCommand(storeInfo));
if (!new File(storeInfo.getName()).exists()) {
commands.get("clear").exec(null);
}
}
public void exec(String[] cmds) {
if (cmds == null || cmds.length < 1) {
System.out.println("no target");
return;
}
List<String> cmdList = Arrays.asList(cmds);
String[] args = cmdList.subList(1, cmdList.size()).toArray(new String[0]);
this.commands.get(cmds[0]).exec(args);
}
}
[Command.java]
public interface Command {
void exec(String[] args);
}
Pour chaque commande, nous faisons de même, sauf que les informations du magasin sont passées du hachage en mémoire à JSON. (Je vais donc omettre l'explication.)
[SaveCommand.java]
import com.google.gson.Gson;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
public class SaveCommand implements Command {
private StoreInfo storeInfo;
public SaveCommand(StoreInfo storeInfo) {
this.storeInfo = storeInfo;
}
@Override
public void exec(String[] args) {
if (args == null || args.length != 2) {
System.out.println("not valid");
return;
}
Gson gson = new Gson();
Path p = Paths.get(this.storeInfo.getName());
try {
Map<String, String> now = gson.fromJson(Files.readAllLines(p).get(0), HashMap.class);
now.put(args[0], args[1]);
Files.write(p, gson.toJson(now).getBytes());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
[GetCommand.java]
import com.google.gson.Gson;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
public class GetCommand implements Command {
private StoreInfo storeInfo;
public GetCommand(StoreInfo storeInfo) {
this.storeInfo = storeInfo;
}
@Override
public void exec(String[] args) {
if (args == null || args.length != 1) {
System.out.println("not valid");
return;
}
Path p = Paths.get(this.storeInfo.getName());
try {
Map<String, String> now = new Gson().fromJson(Files.readAllLines(p).get(0), HashMap.class);
System.out.println(now.get(args[0]));
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
[ListCommand.java]
import com.google.gson.Gson;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
public class ListCommand implements Command {
private StoreInfo storeInfo;
public ListCommand(StoreInfo storeInfo) {
this.storeInfo = storeInfo;
}
@Override
public void exec(String[] args) {
Path p = Paths.get(this.storeInfo.getName());
try {
Map<String, String> now = new Gson().fromJson(Files.readAllLines(p).get(0), HashMap.class);
System.out.println("\"key\",\"value\"");
now.forEach((k, v) -> System.out.printf("\"%s\",\"%s\"\n", k, v));
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
[RemoveCommand.java]
import com.google.gson.Gson;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
public class RemoveCommand implements Command {
private StoreInfo storeInfo;
public RemoveCommand(StoreInfo storeInfo) {
this.storeInfo = storeInfo;
}
@Override
public void exec(String[] args) {
if (args == null || args.length != 1) {
System.out.println("not valid");
return;
}
Gson gson = new Gson();
Path p = Paths.get(this.storeInfo.getName());
try {
Map<String, String> now = gson.fromJson(Files.readAllLines(p).get(0), HashMap.class);
now.remove(args[0]);
Files.write(p, gson.toJson(now).getBytes());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
[ClearCommand.java]
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class ClearCommand implements Command {
private StoreInfo storeInfo;
public ClearCommand(StoreInfo storeInfo) {
this.storeInfo = storeInfo;
}
@Override
public void exec(String[] args) {
try {
Files.write(Paths.get(storeInfo.getName()), "{}".getBytes());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
[HelpCommand.java]
public class HelpCommand implements Command {
@Override
public void exec(String[] args) {
String msg = "\n" +
"[usage]\n" +
"Cette commande gère les informations de chaîne de caractères au format clé-valeur.\n" +
"Les sous-commandes suivantes sont disponibles.\n" +
"\n" +
"save ...Passez la clé et la valeur et enregistrez.\n" +
"get ...Passez la clé pour afficher la valeur.\n" +
"remove ...Passez la clé et supprimez la valeur.\n" +
"list ...Répertorie le contenu enregistré.\n" +
"clear ...Initialise le contenu enregistré.\n" +
"help ...Les informations d'aide (identiques à ce contenu) s'affichent.\n" +
"end ...Quittez l'application.\n" +
"\n";
System.out.println(msg);
}
}
[EndCommand.java]
public class EndCommand implements Command {
@Override
public void exec(String[] args) {
System.out.println("End!");
System.exit(-1);
}
}
Je me rends compte que ça devient de plus en plus compliqué ...