public static String readFile(File file) { try { byte[] encoded = Files.readAllBytes(Paths.get(file.getCanonicalPath())); return StandardCharsets.UTF_8.decode(ByteBuffer.wrap(encoded)).toString(); } catch (IOException e) { return null; } }
/** * function to get the string of the last "*.json"-file within the modulePathOnUSB * * @return string with the contents of the last "*.json"-file within the modulePathOnUSB (in * UTF-8) * @throws Exception FileNotFoundException will occur if the given folder does not exist Exception * will occur if there was no file with the given extension found in the given folder */ public String getJsonFileAsString() throws Exception { try { byte[] encoded = fileToByteArray(modulePathOnUSB + "ModuleData/", "json"); return StandardCharsets.UTF_8.decode(ByteBuffer.wrap(encoded)).toString(); } catch (Exception e) { throw e; } }
/** Gets String contents from channel and closes it. */ public static String getStringContents(ReadableByteChannel channel) throws IOException { // TODO Checks if a supplier would be nice try { ByteBuffer buffer = ByteBuffer.allocate(1024 * 8); StringBuilder sb = new StringBuilder(); int bytesRead = channel.read(buffer); while (bytesRead != -1) { buffer.flip(); CharBuffer charBuffer = StandardCharsets.UTF_8.decode(buffer); sb.append(charBuffer.toString()); buffer.clear(); bytesRead = channel.read(buffer); } return sb.toString(); } finally { channel.close(); } }
private String receive(ByteBuffer buffer) throws IOException { buffer.clear(); channel.receive(buffer); buffer.flip(); return StandardCharsets.UTF_8.decode(buffer).toString(); }
@NotNull protected static String readFile(@NotNull String path) throws IOException { byte[] encoded = Files.readAllBytes(getPath(path)); return StandardCharsets.UTF_8.decode(ByteBuffer.wrap(encoded)).toString(); }