package uk.co.nickthecoder.feather.runtime;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
final public class FileExtensions {
private FileExtensions() {
}
public static String extension(File file) {
String name = file.getName();
int lastDot = name.lastIndexOf('.');
return (lastDot >= 0) ? name.substring(lastDot + 1) : "";
}
public static String nameWithoutExtension(File file) {
String name = file.getName();
int dot = name.lastIndexOf(".");
if (dot > 0) {
return name.substring(0, dot);
} else {
return name;
}
}
public static String pathWithoutExtension(File file) {
String p = file.getParent();
if (p == null) {
return nameWithoutExtension(file);
} else {
return p + File.separator + nameWithoutExtension(file);
}
}
public static boolean isSymlink(File file) throws IOException {
if (file == null)
throw new NullPointerException("File must not be null");
File canon;
if (file.getParent() == null) {
canon = file;
} else {
File canonDir = file.getParentFile().getCanonicalFile();
canon = new File(canonDir, file.getName());
}
return !canon.getCanonicalFile().equals(canon.getAbsoluteFile());
}
// Note, there's a bug in Java 7 on Windows, so upgrade to Java 8 or above.
public static File homeDirectory() {
return new File(java.lang.System.getProperty("user.home"));
}
public static String readText(File file) throws IOException {
return readText(file, StandardCharsets.UTF_8);
}
public static String readText(File file, Charset charset) throws IOException {
try (Reader reader = new InputStreamReader(new FileInputStream(file), charset)) {
StringWriter buffer = new StringWriter();
char[] cArray = new char[1024];
var chars = reader.read(cArray, 0, cArray.length);
while (chars >= 0) {
buffer.write(cArray, 0, chars);
chars = reader.read(cArray, 0, cArray.length);
}
return buffer.toString();
}
}
public static void writeText(File file, String str) throws IOException {
writeText(file, str, StandardCharsets.UTF_8);
}
public static void writeText(File file, String str, Charset charset) throws IOException {
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write(str.getBytes(charset));
}
}
}