]> git.basschouten.com Git - openhab-addons.git/blob
bb6abaf052264e9e02cf0e767c08b91f6c889b3b
[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.mybmw.internal.util;
14
15 import static org.junit.jupiter.api.Assertions.fail;
16
17 import java.io.BufferedReader;
18 import java.io.File;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.io.InputStreamReader;
22
23 import org.eclipse.jdt.annotation.NonNullByDefault;
24 import org.openhab.binding.mybmw.internal.utils.Constants;
25
26 /**
27  * The {@link FileReader} Helper Util to read test resource files
28  *
29  * @author Bernd Weymann - Initial contribution
30  * @author Martin Grassl - added reading of image
31  */
32 @NonNullByDefault
33 public class FileReader {
34
35     /**
36      * reads a file into a string
37      * 
38      * @param filename
39      * @return
40      */
41     public static String fileToString(String filename) {
42         try (BufferedReader br = new BufferedReader(
43                 new InputStreamReader(FileReader.class.getClassLoader().getResourceAsStream(filename), "UTF-8"))) {
44             StringBuilder buf = new StringBuilder();
45             String sCurrentLine;
46
47             while ((sCurrentLine = br.readLine()) != null) {
48                 buf.append(sCurrentLine);
49             }
50             return buf != null ? buf.toString() : "";
51         } catch (IOException e) {
52             fail("Read failure " + filename, e);
53         }
54         return Constants.UNDEF;
55     }
56
57     /**
58      * reads a file into a byte[]
59      * 
60      * @param filename
61      * @return
62      */
63     public static byte[] fileToByteArray(String filename) {
64         File file = new File(filename);
65         byte[] bytes = new byte[(int) file.length()];
66
67         try (InputStream is = (FileReader.class.getClassLoader().getResourceAsStream(filename))) {
68             is.read(bytes);
69         } catch (IOException e) {
70             fail("Read failure " + filename, e);
71         }
72
73         return bytes;
74     }
75 }