123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665 |
- /*
- * Copyright (C) 2015 iZc
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
- package de.nplusc.izc.tools.IOtools;
- import de.nplusc.izc.tools.baseTools.Tools;
- import java.io.*;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- import java.nio.CharBuffer;
- import java.nio.channels.FileChannel;
- import java.nio.charset.StandardCharsets;
- import java.util.ArrayList;
- import java.util.Arrays;
- import org.apache.logging.log4j.LogManager;
- import org.apache.logging.log4j.Logger;
- /**
- *
- * @author LH
- */
- public class FileTK
- {
-
- private static final Logger l = LogManager.getLogger();
- protected FileTK()
- {
- }
- /**
- * Erzeugt die Verzeichnisse die nötig sind um das File zuspeichern
- *
- * @param f File zum abarbeiten
- */
- public static void ensuredirExistence(File f)
- {
- File fp = f.getParentFile();
- if (!fp.exists())
- {
- fp.mkdirs();
- }
- }
- /**
- * Erzeugt die Verzeichnisse die nötig sind um das File zuspeichern
- *
- * @param path Path zum abarbeiten
- */
- public static void ensuredirExistence(String path)
- {
- ensuredirExistence(new File(path));
- }
- /**
- * Hangelt sich rekursiv durch ein Verzeichnis und listet alles
- * darunterliegende auf(begrenzt auf 40 Ebenen)
- *
- * @param path WO begonnen werden soll
- * @return Liste der Pfae
- */
- public static String[] walkDirectoryRecursively(String path)
- {
- return walkDirectoryRecursively(path, 40);
- }
- /**
- * Hangelt sich rekursiv durch ein Verzeichnis und listet alles
- * darunterliegende auf(begrenzt auf 40 Ebenen)
- *
- * @param path WO begonnen werden soll
- * @param verbose Geschwätzig?
- * @return Liste der Pfae
- */
- public static String[] walkDirectoryRecursively(String path, boolean verbose)
- {
- return walkDirectoryRecursively(path, 40, verbose);
- }
-
-
-
-
-
- /**
- * Hangelt sich rekursiv durch ein Verzeichnis und listet alles
- * darunterliegende auf
- *
- * @param path WO begonnen werden soll
- * @param recurseDepth Wieviele ebenen
- * @return Liste der Pfae
- */
- public static String[] walkDirectoryRecursively(String path, int recurseDepth)
- {
- return walkDirectoryRecursively(path, recurseDepth, false);
- }
- /**
- * Hangelt sich rekursiv durch ein Verzeichnis und listet alles
- * darunterliegende auf
- *
- * @param path WO begonnen werden soll
- * @param recurseDepth Wieviele ebenen
- * @param verbose Geschwätzig?
- * @return Liste der Pfae
- */
- public static String[] walkDirectoryRecursively(String path, int recurseDepth, boolean verbose)
- {
- //if(verbose)
- //System.out.print("cls\r\n");//DOESNTWORK:(
- ArrayList<String> data = new ArrayList<>();
- int length = 0;
- String[] DirCnt = getDirectoryContent(path);
- if(DirCnt==null)
- {
- return new String[]{};
- }
- for (String string : DirCnt)
- {
- File f = new File(string);
- if (f.isDirectory())
- {
- if (verbose)
- {
- //System.console().
- /*String s2 = "";//Satz mit X war wohl nix
- while(s2.length()<length)
- {
- s2+="\b";//weigert sich ne zeile nauf zu gehren
- }
- System.out.print(s2);
- System.console().writer().append(s2);*/
- String s = "\rReading in:" + f.getPath();
- //NOLOG
- System.out.print(s);
- /*try //abgekrachte FLiegenklatsche
- {
- Thread.sleep(20);
- }
- catch (InterruptedException ex)
- {
- ex.printStackTrace();
- }
- */
- if(s.length()>length)
- {
- length = s.length();
- }
- else
- {
- while(s.length()<length)
- {
- s+=" ";//auffüllen auf gewünschte länge....
- }
- }
- // System.out.print((char)0x1b+"[u");//DOESNTWORK
- }
- String[] sdc = walkDirectoryRecursively(string, recurseDepth - 1,verbose);
- data.add(string);
- data.addAll(Arrays.asList(sdc));
- }
- else
- {
- data.add(string);
- }
- }
- String[] s = new String[]
- {
- ""
- };
- return data.toArray(s);
- }
- /**
- * Liest Dateiname mit Erweiterung aus
- * @param path Pfad derDatei
- * @return Dateiname ohne Pfad
- */
-
- public static String getFileName(String path)
- {
- //String ft1 = FileTK.getFilePath(path);
- String ft2 = path.substring(path.lastIndexOf("\\")+1);
- return ft2;
- }
-
- /**
- * Liest dateiendung aus
- *
- * @param path Dateipfad zumauslesen
- * @return dateiendung in lowercase
- */
- public static String getFileExt(String path)
- {
- String ext = null;
- int i = path.lastIndexOf('.');
- if (i > 0 && i < path.length() - 1)
- {
- ext = path.substring(i + 1).toLowerCase();
- }
- return ext;
- /*
- String[] splitpath = path.split(".");
- String ret = null;
- if(splitpath.length>1)
- {
- ret = splitpath[splitpath.length-1];
- }
- return ret;*/
- }
- /**
- * Gibt Ordnerpfad netr datei aus
- *
- * @param path Dateiname/pfd
- * @return Ordner der Datei
- */
- public static String getFilePath(String path)
- {
- path = new File(path).getAbsolutePath();//falls nen relativer Pfad verwendet wurde
- String ext = path;
- int i = path.lastIndexOf("\\");
- if (i > 0 && i < path.length())
- {
- ext = path.substring(0, i);
- }
- return ext;
- }
- /*private static void log(String line)
- {
- Tools.DebugHelperPrint(line, true, "Toolkit.enableCoreDebug");
- }*/
- /**
- * Lädt Datei in String-array
- *
- * @param path Dateipfad
- * @return ZEilenweises Array der Datei
- */
- @SuppressWarnings("ConvertToTryWithResources")
- public static String[] fileload(String path)
- {
- return fileload(path, true);
- }
- /**
- * Lädt Datei in String-array
- *
- * @param path Dateipfad
- * @param eofmark unbenutzt (zu fixen wegen bug)
- * @return ZEilenweises Array der Datei
- */
- @SuppressWarnings("ConvertToTryWithResources")
- public static String[] fileload(String path, boolean eofmark)//bugfix noch zu erledigen
- {
- String filedata = "";
- String[] filecnt;
- try
- {
- FileReader fr = new FileReader(path);
- BufferedReader br = new BufferedReader(fr);
- filedata = br.readLine() + "\n";
- String zeile = "x";
- while (zeile != null)
- {
- l.trace(zeile);
- zeile = br.readLine();
- filedata = filedata + zeile + "\n";
- }
- filecnt = filedata.split("\n");
- fr.close();
- }
- catch (Exception ioe)
- {
- //log("Failed to load FIle:unknown error. Something f@ild.");
- l.info("noncritical internal error. Ignored");
- l.info("@:"+new File(path).getAbsolutePath());
- //ioe.printStackTrace();
- filecnt = new String[1];
- filecnt[0] = "LMAA";
- }
- l.trace(filedata);
- return filecnt;
- }
- /**
- * Speichert Datei(überschreibend)
- *
- * @param cnt Inhalt
- * @param path Wohin
- */
- public static void writeFile(String cnt, String path)
- {
- writeFile(cnt, path, false);
- }
- /**
- * Speichert Datei
- *
- * @param cnt Inhalt
- * @param path Wohin
- * @param app Anfügen?
- */
- @SuppressWarnings("CallToThreadDumpStack")
- public static void writeFile(String cnt, String path, boolean app)
- {
-
- Writer fw = null;
- try
- {
- new File(path).createNewFile();
- fw = new OutputStreamWriter(new FileOutputStream(path), StandardCharsets.UTF_8);
- //fstream = new OutputStreamWriter(new FileOutputStream(mergedFile), StandardCharsets.UTF_8);
- if (!app)
- {
- fw.write(cnt);
- }
- else
- {
- int size = (int) new File(path).length();
- fw.write(path, size, cnt.length());
- }
- }
- catch (IOException e)
- {
- l.warn("Konnte Datei nicht erstellen");
- e.printStackTrace();
- }
- finally
- {
- if (fw != null)
- {
- try
- {
- fw.close();
- }
- catch (IOException e)
- {
- }
- }
- }
- }
- /**
- * Prüft auf existenz ner datei/Verzeichnis
- *
- * @param path Was
- * @return Obs existiert
- */
- public static boolean checkDirExist(String path)
- {
- File f = new File(path);
- if (!f.exists())
- {
- return false;
- }
- return true;
- }
- /**
- * entspricht dir von der cmd
- *
- * @param path Wo
- * @return Array der dateien innerhalb
- */
- public static String[] getDirectoryContent(String path)
- {
- return getDirectoryContent(path,false);
- }
- /**
- * entspricht dir von der cmd
- *
- * @param path Wo
- * @param skipPrePath ob nur die t dateinamen kommen sollen;
- * @return Array der dateien innerhalb
- */
- public static String[] getDirectoryContent(String path,boolean skipPrePath)
- {
- File f = new File(path);
- File[] dirtmpf = f.listFiles();
- //String[] dirtmp = new String[] d
- l.trace("Pfad={}",path);
- String[] ret = null;
- try
- {
- ret = new String[dirtmpf.length];
- int j;
- for (int i = 0; i < dirtmpf.length; i++)
- {
- j = i;
- String tmp = dirtmpf[i].getPath();
- if (!(tmp.length() < path.length()))
- {
-
- ret[j] = tmp;
- if(skipPrePath)
- {
- ret[j] = getFileName(tmp);
- }
-
-
- //j++;
- }
- }
- }
- catch (NullPointerException e)
- {
- ret = new String[0];
- l.trace("LMAA|{}",path);
- }
- return ret;
- }
- /**
- * internal flag that caches that a catch block triggered and disables the reflection on the path class
- */
- private static boolean blockNewpathMethod=false;
-
- /**
- * Erzeugt den relativen Pfad einer datei/eines Ordners zu eienm Basispfad
- *
- * @param absolutePath Pfad von dem relativer Pfad zu
- * @param basePath diesem ermittelt werden soll
- * @return der relative Pfad
- */
- public static String getRelativePath(String absolutePath, String basePath)//Initializer für Hack!
- {
- String rpath =null;
- if(!blockNewpathMethod)
- {
- //reflection für neuere Java-Klassen
- try
- {
- Class pathclass = Class.forName("java.nio.file.Path");
- Object basepath = null;
- File magix = new File(basePath);
- Method pfadheraberdalli = File.class.getMethod("toPath");
- basepath = pfadheraberdalli.invoke(magix);
-
- Method rel=pathclass.getMethod("relativize", (Class)pathclass);
- File current = new File(absolutePath);
- Object pa = pfadheraberdalli.invoke(current);
- l.trace("pa-Class:"+pa.getClass());
- rpath = rel.invoke(basepath, pa)+"";
- }
- catch(ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException| InvocationTargetException ex)
- {
- blockNewpathMethod=true; //abklemmen der klassentestung.
- }
- }
-
- //continue with fallback incase the new method doesn't work.
- if(rpath!=null)
- {
- return rpath;
- }
- absolutePath = absolutePath.replace("/", "\\");
- basePath = basePath.replace("/", "\\");
- rpath = getRelativePath(absolutePath, basePath, 0);
- return rpath==null?rpath:rpath.replace("\\", File.separator);
- }
- private static String getRelativePath(String absolutePath, String basePath, int recurses)//Fetter Hack wegen fehkendem Java-Befehl!
- {
- String replace = null, unRegex = null, internalPath = "", parsedPath = "";
- boolean err = false;
-
- if (absolutePath != null || basePath != null)
- {
- if (recurses > 0)
- {
- try
- {
- String pathSplit[] = basePath.split("\\\\");
- Object[] psplit = Tools.truncateArray(pathSplit, 1, true);
- for (Object o : psplit)
- {
- internalPath += o + "\\";
- }
- //entfernt das letze element des pfades
- //BSP: C:\pfad\zu\krempel\killme -> C:\pfad\zu\krempel
- //Kilme wird entfernt
-
- String replaceTemp = "";
- for (int i = 0; i < recurses; i++)//recurses gibt an wievile ebenen er rauf ist
- {
- replaceTemp += "\\.\\.\\\\"; // ..\ so oft wie der parser den baum raufgewandert ist
- }
- replace = "\\.\\\\" + replaceTemp; //beginnt pfad mit .\ und dann soviele ..\-s wie nötig
- unRegex = internalPath.replaceAll("\\\\", "\\\\\\\\"); // \ -> \\
- l.trace("Aha");
- }
- catch (Exception ex)
- {
- err = true;
- l.trace("FickDich");
- }
- }
- else
- {
- internalPath = basePath;
- replace = "\\.\\\\";
- unRegex = basePath.replaceAll("\\\\", "\\\\\\\\"); // \ -> \\
- }
- parsedPath = absolutePath.replaceAll(unRegex, replace);// basePath -> .\ haut den gemeinsamen teil raus und fügt den relativteil an
- l.trace("ParsedPath={}",parsedPath);
- if (parsedPath.equals(absolutePath))
- {
- //basePath=internalPath;
- recurses++;
- String parsedPath2 = null;
- //absolutePath = absolutePath.replaceAll("\\\\", "\\\\\\\\");
- try
- {
- parsedPath2 = getRelativePath(absolutePath, internalPath, recurses);
- }
- catch (Exception ex)
- {
- l.trace("Arschfotze");
- }
- if (parsedPath2 != null)
- {
- parsedPath = parsedPath2;
- }
- }
- }
- else
- {
- err = false;
- }
- if (err == true)
- {
- parsedPath = null;
- }
-
- return parsedPath;
- }
- /**
- * Fatei kopieren
- * Code ist ausm netz: http://www.javabeginners.de/Dateien_und_Verzeichnisse/Eine_Datei_kopieren.php
- * @param in Eingabefile
- * @param out Ausgabefile
- * @throws IOException
- */
-
- public static void kopierpaste(File in, File out) //throws IOException
- {
- FileChannel inChannel=null,outChannel=null;
- try
- {
- inChannel = new FileInputStream(in).getChannel();
- outChannel = new FileOutputStream(out).getChannel();
- inChannel.transferTo(0, inChannel.size(), outChannel);
- }
- catch (IOException e)
- {
- e.printStackTrace();
- l.error("Kopiererei geerrort");
- // throw e;
- }
- finally
- {
- if (inChannel != null)
- {
- try
- {
- inChannel.close();
- }
- catch (IOException ex)
- {
- ex.printStackTrace();
- }
- }
- if (outChannel != null)
- {
- try
- {
- outChannel.close();
- }
- catch (IOException ex)
- {
- ex.printStackTrace();
- }
- }
- }
- }
-
- /**
- * Checkt ob pfad nen verzeichnis sit
- * @param path welcher pfad
- * @return ja/nein
- */
- public static boolean isDir(String path)
- {
- return new File(path).isDirectory();
- }
-
- /**
- * Schrubbt verzeichnis rekursiv raus;
- * @param path welches dir
- */
-
- public static void verzeichnisKillen(File path)
- {
- if(path.exists())
- {
- for (File file : path.listFiles())
- {
- if (file.isDirectory())
- {
- verzeichnisKillen(file);
- }
- file.delete();
- }
- path.delete();
- }
- }
-
-
- public static String fileAsString(String path) throws FileNotFoundException, IOException
- {
- return fileAsString(new File(path));
- }
-
- public static String fileAsString(File path) throws FileNotFoundException, IOException
- {
- if(path.length()>Integer.MAX_VALUE)
- {
- throw new IOException(" File too large for specified operation");
- }
- FileReader fr = new FileReader(path);
- CharBuffer c = CharBuffer.allocate((int)path.length());
- fr.read(c);
- c.rewind();
- l.trace(path.length()+"|"+c.length());
- return c.toString();
- }
-
- }
|