From 7cee82a5c375b229dae3626703c9b4bb1dc0a136 Mon Sep 17 00:00:00 2001 From: WickedJack99 Date: Thu, 4 Apr 2024 22:13:42 +0200 Subject: [PATCH] Added function to create peer config file. --- .../FileReaderWriter/FileReaderWriter.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/src/main/java/vslab1/src/FileReaderWriter/FileReaderWriter.java b/src/main/java/vslab1/src/FileReaderWriter/FileReaderWriter.java index f7ca8d0..0117b69 100644 --- a/src/main/java/vslab1/src/FileReaderWriter/FileReaderWriter.java +++ b/src/main/java/vslab1/src/FileReaderWriter/FileReaderWriter.java @@ -1,5 +1,10 @@ package vslab1.src.FileReaderWriter; +import java.io.File; +import java.io.IOException; +import java.nio.file.*; + +import vslab1.src.Constants; import vslab1.src.Peers.EOnlineState; import vslab1.src.Peers.Peer; @@ -12,6 +17,42 @@ public class FileReaderWriter { private static Peer thisPeerBuffer = null; + /** + * Creates directories at given path and file where info about this and other peers is getting stored. + * @param filesPath the path where to find or create the info files. + */ + public static void createInfoFilesIfNotExisting(String filesPath) { + Path path = Paths.get(filesPath); + boolean validPath = true; + if (!Files.exists(path)) { + try { + Files.createDirectories(path); + System.out.println("Directories created successfully."); + } catch (Exception e) { + System.out.println("Failed to create directories: " + e.getMessage()); + validPath = false; + } + } + if (validPath) { + String appendix = null; + if (filesPath.endsWith(File.separator)) { + appendix = ""; + } else { + appendix = File.separator; + } + Path peerFilePath = Paths.get(filesPath + appendix + Constants.PEERCONFIGFILENAME); + if (!Files.exists(peerFilePath)) { + try { + Files.createFile(peerFilePath); + System.out.println("Created " + Constants.PEERCONFIGFILENAME + " file."); + } catch (IOException e) { + System.out.println("Failed to create " + Constants.PEERCONFIGFILENAME + " file."); + e.printStackTrace(); + } + } + } + } + public static Peer getThisPeer(EUpdated updateState) { switch (updateState) { case NotUpdated: { @@ -35,6 +76,7 @@ public class FileReaderWriter { // TODO unimplemented // read from file this peers data + String ipAddress = null; int port = 5000; thisPeerBuffer = new Peer(ipAddress, port, null, EOnlineState.Online); // change to valid data once implemented