]> git.basschouten.com Git - openhab-addons.git/blob
be9c3d019aabc50d6aed0e04ddd31d3c76b55e60
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.folderwatcher.internal.common;
14
15 import java.io.BufferedWriter;
16 import java.io.File;
17 import java.io.FileWriter;
18 import java.io.IOException;
19 import java.nio.file.Files;
20 import java.util.List;
21
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23
24 /**
25  * The {@link WatcherCommon} class contains commonly used methods.
26  *
27  * @author Alexandr Salamatov - Initial contribution
28  */
29 @NonNullByDefault
30 public class WatcherCommon {
31
32     private static void initFile(File file, String watchDir) throws IOException {
33         try (BufferedWriter fileWriter = new BufferedWriter(new FileWriter(file))) {
34             fileWriter.write(watchDir);
35             fileWriter.newLine();
36         }
37     }
38
39     public static List<String> initStorage(File file, String watchDir) throws IOException {
40         List<String> returnList = List.of();
41         List<String> currentFileListing = List.of();
42         if (!file.exists()) {
43             Files.createDirectories(file.toPath().getParent());
44             initFile(file, watchDir);
45         } else {
46             currentFileListing = Files.readAllLines(file.toPath().toAbsolutePath());
47             if (currentFileListing.get(0).equals(watchDir)) {
48                 returnList = currentFileListing;
49             } else {
50                 initFile(file, watchDir);
51             }
52         }
53         return returnList;
54     }
55
56     public static void saveNewListing(List<String> newList, File listingFile) throws IOException {
57         try (BufferedWriter fileWriter = new BufferedWriter(new FileWriter(listingFile, true))) {
58             for (String newFile : newList) {
59                 fileWriter.write(newFile);
60                 fileWriter.newLine();
61             }
62         }
63     }
64 }