package net.knarcraft.stargate.utility; import net.md_5.bungee.api.ChatColor; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; /** * Helper class for reading files */ public final class FileHelper { private FileHelper() { } /** * Gets an input stream from a string pointing to an internal file * *
This is used for getting an input stream for reading a file contained within the compiled .jar file. The file * should be in the resources directory, and the file path should start with a forward slash ("/") character.
* * @param fileThe file to read
* @returnAn input stream for the file
*/ public static InputStream getInputStreamForInternalFile(String file) { return FileHelper.class.getResourceAsStream(file); } /** * Gets a buffered reader from a string pointing to a file * * @param fileThe file to read
* @returnA buffered reader reading the file
* @throws FileNotFoundExceptionIf the given file does not exist
*/ public static BufferedReader getBufferedReaderFromString(String file) throws FileNotFoundException { FileInputStream fileInputStream = new FileInputStream(file); return getBufferedReaderFromInputStream(fileInputStream); } /** * Gets a buffered reader given an input stream * * @param inputStreamThe input stream to read
* @returnA buffered reader reading the input stream
*/ public static BufferedReader getBufferedReaderFromInputStream(InputStream inputStream) { InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8); return new BufferedReader(inputStreamReader); } /** * Gets a buffered writer from a string pointing to a file * * @param fileThe file to write to
* @returnA buffered writer writing to the file
* @throws FileNotFoundExceptionIf the file does not exist
*/ public static BufferedWriter getBufferedWriterFromString(String file) throws FileNotFoundException { FileOutputStream fileOutputStream = new FileOutputStream(file); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8); return new BufferedWriter(outputStreamWriter); } /** * Reads key/value pairs from an input stream * * @param bufferedReaderThe buffered reader to read
* @returnA map containing the read pairs
* @throws IOExceptionIf unable to read from the stream
*/ public static MapThe string to remove the BOM from
* @returnA string guaranteed without a BOM
*/ private static String removeUTF8BOM(String string) { String UTF8_BOM = "\uFEFF"; if (string.startsWith(UTF8_BOM)) { string = string.substring(1); } return string; } }