FileTK.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. /*
  2. * Copyright (C) 2015 iZc
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. package de.nplusc.izc.tools.IOtools;
  18. import de.nplusc.izc.tools.baseTools.Tools;
  19. import java.io.*;
  20. import java.lang.reflect.InvocationTargetException;
  21. import java.lang.reflect.Method;
  22. import java.nio.CharBuffer;
  23. import java.nio.channels.FileChannel;
  24. import java.nio.charset.StandardCharsets;
  25. import java.util.ArrayList;
  26. import java.util.Arrays;
  27. import org.apache.logging.log4j.LogManager;
  28. import org.apache.logging.log4j.Logger;
  29. /**
  30. *
  31. * @author LH
  32. */
  33. public class FileTK
  34. {
  35. private static final Logger l = LogManager.getLogger();
  36. protected FileTK()
  37. {
  38. }
  39. /**
  40. * Erzeugt die Verzeichnisse die nötig sind um das File zuspeichern
  41. *
  42. * @param f File zum abarbeiten
  43. */
  44. public static void ensuredirExistence(File f)
  45. {
  46. File fp = f.getParentFile();
  47. if (!fp.exists())
  48. {
  49. fp.mkdirs();
  50. }
  51. }
  52. /**
  53. * Erzeugt die Verzeichnisse die nötig sind um das File zuspeichern
  54. *
  55. * @param path Path zum abarbeiten
  56. */
  57. public static void ensuredirExistence(String path)
  58. {
  59. ensuredirExistence(new File(path));
  60. }
  61. /**
  62. * Hangelt sich rekursiv durch ein Verzeichnis und listet alles
  63. * darunterliegende auf(begrenzt auf 40 Ebenen)
  64. *
  65. * @param path WO begonnen werden soll
  66. * @return Liste der Pfae
  67. */
  68. public static String[] walkDirectoryRecursively(String path)
  69. {
  70. return walkDirectoryRecursively(path, 40);
  71. }
  72. /**
  73. * Hangelt sich rekursiv durch ein Verzeichnis und listet alles
  74. * darunterliegende auf(begrenzt auf 40 Ebenen)
  75. *
  76. * @param path WO begonnen werden soll
  77. * @param verbose Geschwätzig?
  78. * @return Liste der Pfae
  79. */
  80. public static String[] walkDirectoryRecursively(String path, boolean verbose)
  81. {
  82. return walkDirectoryRecursively(path, 40, verbose);
  83. }
  84. /**
  85. * Hangelt sich rekursiv durch ein Verzeichnis und listet alles
  86. * darunterliegende auf
  87. *
  88. * @param path WO begonnen werden soll
  89. * @param recurseDepth Wieviele ebenen
  90. * @return Liste der Pfae
  91. */
  92. public static String[] walkDirectoryRecursively(String path, int recurseDepth)
  93. {
  94. return walkDirectoryRecursively(path, recurseDepth, false);
  95. }
  96. /**
  97. * Hangelt sich rekursiv durch ein Verzeichnis und listet alles
  98. * darunterliegende auf
  99. *
  100. * @param path WO begonnen werden soll
  101. * @param recurseDepth Wieviele ebenen
  102. * @param verbose Geschwätzig?
  103. * @return Liste der Pfae
  104. */
  105. public static String[] walkDirectoryRecursively(String path, int recurseDepth, boolean verbose)
  106. {
  107. //if(verbose)
  108. //System.out.print("cls\r\n");//DOESNTWORK:(
  109. ArrayList<String> data = new ArrayList<>();
  110. int length = 0;
  111. String[] DirCnt = getDirectoryContent(path);
  112. if(DirCnt==null)
  113. {
  114. return new String[]{};
  115. }
  116. for (String string : DirCnt)
  117. {
  118. File f = new File(string);
  119. if (f.isDirectory())
  120. {
  121. if (verbose)
  122. {
  123. //System.console().
  124. /*String s2 = "";//Satz mit X war wohl nix
  125. while(s2.length()<length)
  126. {
  127. s2+="\b";//weigert sich ne zeile nauf zu gehren
  128. }
  129. System.out.print(s2);
  130. System.console().writer().append(s2);*/
  131. String s = "\rReading in:" + f.getPath();
  132. //NOLOG
  133. System.out.print(s);
  134. /*try //abgekrachte FLiegenklatsche
  135. {
  136. Thread.sleep(20);
  137. }
  138. catch (InterruptedException ex)
  139. {
  140. ex.printStackTrace();
  141. }
  142. */
  143. if(s.length()>length)
  144. {
  145. length = s.length();
  146. }
  147. else
  148. {
  149. while(s.length()<length)
  150. {
  151. s+=" ";//auffüllen auf gewünschte länge....
  152. }
  153. }
  154. // System.out.print((char)0x1b+"[u");//DOESNTWORK
  155. }
  156. String[] sdc = walkDirectoryRecursively(string, recurseDepth - 1,verbose);
  157. data.add(string);
  158. data.addAll(Arrays.asList(sdc));
  159. }
  160. else
  161. {
  162. data.add(string);
  163. }
  164. }
  165. String[] s = new String[]
  166. {
  167. ""
  168. };
  169. return data.toArray(s);
  170. }
  171. /**
  172. * Liest Dateiname mit Erweiterung aus
  173. * @param path Pfad derDatei
  174. * @return Dateiname ohne Pfad
  175. */
  176. public static String getFileName(String path)
  177. {
  178. //String ft1 = FileTK.getFilePath(path);
  179. String ft2 = path.substring(path.lastIndexOf("\\")+1);
  180. return ft2;
  181. }
  182. /**
  183. * Liest dateiendung aus
  184. *
  185. * @param path Dateipfad zumauslesen
  186. * @return dateiendung in lowercase
  187. */
  188. public static String getFileExt(String path)
  189. {
  190. String ext = null;
  191. int i = path.lastIndexOf('.');
  192. if (i > 0 && i < path.length() - 1)
  193. {
  194. ext = path.substring(i + 1).toLowerCase();
  195. }
  196. return ext;
  197. /*
  198. String[] splitpath = path.split(".");
  199. String ret = null;
  200. if(splitpath.length>1)
  201. {
  202. ret = splitpath[splitpath.length-1];
  203. }
  204. return ret;*/
  205. }
  206. /**
  207. * Gibt Ordnerpfad netr datei aus
  208. *
  209. * @param path Dateiname/pfd
  210. * @return Ordner der Datei
  211. */
  212. public static String getFilePath(String path)
  213. {
  214. path = new File(path).getAbsolutePath();//falls nen relativer Pfad verwendet wurde
  215. String ext = path;
  216. int i = path.lastIndexOf("\\");
  217. if (i > 0 && i < path.length())
  218. {
  219. ext = path.substring(0, i);
  220. }
  221. return ext;
  222. }
  223. /*private static void log(String line)
  224. {
  225. Tools.DebugHelperPrint(line, true, "Toolkit.enableCoreDebug");
  226. }*/
  227. /**
  228. * Lädt Datei in String-array
  229. *
  230. * @param path Dateipfad
  231. * @return ZEilenweises Array der Datei
  232. */
  233. @SuppressWarnings("ConvertToTryWithResources")
  234. public static String[] fileload(String path)
  235. {
  236. return fileload(path, true);
  237. }
  238. /**
  239. * Lädt Datei in String-array
  240. *
  241. * @param path Dateipfad
  242. * @param eofmark unbenutzt (zu fixen wegen bug)
  243. * @return ZEilenweises Array der Datei
  244. */
  245. @SuppressWarnings("ConvertToTryWithResources")
  246. public static String[] fileload(String path, boolean eofmark)//bugfix noch zu erledigen
  247. {
  248. String filedata = "";
  249. String[] filecnt;
  250. try
  251. {
  252. FileReader fr = new FileReader(path);
  253. BufferedReader br = new BufferedReader(fr);
  254. filedata = br.readLine() + "\n";
  255. String zeile = "x";
  256. while (zeile != null)
  257. {
  258. l.trace(zeile);
  259. zeile = br.readLine();
  260. filedata = filedata + zeile + "\n";
  261. }
  262. filecnt = filedata.split("\n");
  263. fr.close();
  264. }
  265. catch (Exception ioe)
  266. {
  267. //log("Failed to load FIle:unknown error. Something f@ild.");
  268. l.info("noncritical internal error. Ignored");
  269. l.info("@:"+new File(path).getAbsolutePath());
  270. //ioe.printStackTrace();
  271. filecnt = new String[1];
  272. filecnt[0] = "LMAA";
  273. }
  274. l.trace(filedata);
  275. return filecnt;
  276. }
  277. /**
  278. * Speichert Datei(überschreibend)
  279. *
  280. * @param cnt Inhalt
  281. * @param path Wohin
  282. */
  283. public static void writeFile(String cnt, String path)
  284. {
  285. writeFile(cnt, path, false);
  286. }
  287. /**
  288. * Speichert Datei
  289. *
  290. * @param cnt Inhalt
  291. * @param path Wohin
  292. * @param app Anfügen?
  293. */
  294. @SuppressWarnings("CallToThreadDumpStack")
  295. public static void writeFile(String cnt, String path, boolean app)
  296. {
  297. Writer fw = null;
  298. try
  299. {
  300. new File(path).createNewFile();
  301. fw = new OutputStreamWriter(new FileOutputStream(path), StandardCharsets.UTF_8);
  302. //fstream = new OutputStreamWriter(new FileOutputStream(mergedFile), StandardCharsets.UTF_8);
  303. if (!app)
  304. {
  305. fw.write(cnt);
  306. }
  307. else
  308. {
  309. int size = (int) new File(path).length();
  310. fw.write(path, size, cnt.length());
  311. }
  312. }
  313. catch (IOException e)
  314. {
  315. l.warn("Konnte Datei nicht erstellen");
  316. e.printStackTrace();
  317. }
  318. finally
  319. {
  320. if (fw != null)
  321. {
  322. try
  323. {
  324. fw.close();
  325. }
  326. catch (IOException e)
  327. {
  328. }
  329. }
  330. }
  331. }
  332. /**
  333. * Prüft auf existenz ner datei/Verzeichnis
  334. *
  335. * @param path Was
  336. * @return Obs existiert
  337. */
  338. public static boolean checkDirExist(String path)
  339. {
  340. File f = new File(path);
  341. if (!f.exists())
  342. {
  343. return false;
  344. }
  345. return true;
  346. }
  347. /**
  348. * entspricht dir von der cmd
  349. *
  350. * @param path Wo
  351. * @return Array der dateien innerhalb
  352. */
  353. public static String[] getDirectoryContent(String path)
  354. {
  355. return getDirectoryContent(path,false);
  356. }
  357. /**
  358. * entspricht dir von der cmd
  359. *
  360. * @param path Wo
  361. * @param skipPrePath ob nur die t dateinamen kommen sollen;
  362. * @return Array der dateien innerhalb
  363. */
  364. public static String[] getDirectoryContent(String path,boolean skipPrePath)
  365. {
  366. File f = new File(path);
  367. File[] dirtmpf = f.listFiles();
  368. //String[] dirtmp = new String[] d
  369. l.trace("Pfad={}",path);
  370. String[] ret = null;
  371. try
  372. {
  373. ret = new String[dirtmpf.length];
  374. int j;
  375. for (int i = 0; i < dirtmpf.length; i++)
  376. {
  377. j = i;
  378. String tmp = dirtmpf[i].getPath();
  379. if (!(tmp.length() < path.length()))
  380. {
  381. ret[j] = tmp;
  382. if(skipPrePath)
  383. {
  384. ret[j] = getFileName(tmp);
  385. }
  386. //j++;
  387. }
  388. }
  389. }
  390. catch (NullPointerException e)
  391. {
  392. ret = new String[0];
  393. l.trace("LMAA|{}",path);
  394. }
  395. return ret;
  396. }
  397. /**
  398. * internal flag that caches that a catch block triggered and disables the reflection on the path class
  399. */
  400. private static boolean blockNewpathMethod=false;
  401. /**
  402. * Erzeugt den relativen Pfad einer datei/eines Ordners zu eienm Basispfad
  403. *
  404. * @param absolutePath Pfad von dem relativer Pfad zu
  405. * @param basePath diesem ermittelt werden soll
  406. * @return der relative Pfad
  407. */
  408. public static String getRelativePath(String absolutePath, String basePath)//Initializer für Hack!
  409. {
  410. String rpath =null;
  411. if(!blockNewpathMethod)
  412. {
  413. //reflection für neuere Java-Klassen
  414. try
  415. {
  416. Class pathclass = Class.forName("java.nio.file.Path");
  417. Object basepath = null;
  418. File magix = new File(basePath);
  419. Method pfadheraberdalli = File.class.getMethod("toPath");
  420. basepath = pfadheraberdalli.invoke(magix);
  421. Method rel=pathclass.getMethod("relativize", (Class)pathclass);
  422. File current = new File(absolutePath);
  423. Object pa = pfadheraberdalli.invoke(current);
  424. l.trace("pa-Class:"+pa.getClass());
  425. rpath = rel.invoke(basepath, pa)+"";
  426. }
  427. catch(ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException| InvocationTargetException ex)
  428. {
  429. blockNewpathMethod=true; //abklemmen der klassentestung.
  430. }
  431. }
  432. //continue with fallback incase the new method doesn't work.
  433. if(rpath!=null)
  434. {
  435. return rpath;
  436. }
  437. absolutePath = absolutePath.replace("/", "\\");
  438. basePath = basePath.replace("/", "\\");
  439. rpath = getRelativePath(absolutePath, basePath, 0);
  440. return rpath==null?rpath:rpath.replace("\\", File.separator);
  441. }
  442. private static String getRelativePath(String absolutePath, String basePath, int recurses)//Fetter Hack wegen fehkendem Java-Befehl!
  443. {
  444. String replace = null, unRegex = null, internalPath = "", parsedPath = "";
  445. boolean err = false;
  446. if (absolutePath != null || basePath != null)
  447. {
  448. if (recurses > 0)
  449. {
  450. try
  451. {
  452. String pathSplit[] = basePath.split("\\\\");
  453. Object[] psplit = Tools.truncateArray(pathSplit, 1, true);
  454. for (Object o : psplit)
  455. {
  456. internalPath += o + "\\";
  457. }
  458. //entfernt das letze element des pfades
  459. //BSP: C:\pfad\zu\krempel\killme -> C:\pfad\zu\krempel
  460. //Kilme wird entfernt
  461. String replaceTemp = "";
  462. for (int i = 0; i < recurses; i++)//recurses gibt an wievile ebenen er rauf ist
  463. {
  464. replaceTemp += "\\.\\.\\\\"; // ..\ so oft wie der parser den baum raufgewandert ist
  465. }
  466. replace = "\\.\\\\" + replaceTemp; //beginnt pfad mit .\ und dann soviele ..\-s wie nötig
  467. unRegex = internalPath.replaceAll("\\\\", "\\\\\\\\"); // \ -> \\
  468. l.trace("Aha");
  469. }
  470. catch (Exception ex)
  471. {
  472. err = true;
  473. l.trace("FickDich");
  474. }
  475. }
  476. else
  477. {
  478. internalPath = basePath;
  479. replace = "\\.\\\\";
  480. unRegex = basePath.replaceAll("\\\\", "\\\\\\\\"); // \ -> \\
  481. }
  482. parsedPath = absolutePath.replaceAll(unRegex, replace);// basePath -> .\ haut den gemeinsamen teil raus und fügt den relativteil an
  483. l.trace("ParsedPath={}",parsedPath);
  484. if (parsedPath.equals(absolutePath))
  485. {
  486. //basePath=internalPath;
  487. recurses++;
  488. String parsedPath2 = null;
  489. //absolutePath = absolutePath.replaceAll("\\\\", "\\\\\\\\");
  490. try
  491. {
  492. parsedPath2 = getRelativePath(absolutePath, internalPath, recurses);
  493. }
  494. catch (Exception ex)
  495. {
  496. l.trace("Arschfotze");
  497. }
  498. if (parsedPath2 != null)
  499. {
  500. parsedPath = parsedPath2;
  501. }
  502. }
  503. }
  504. else
  505. {
  506. err = false;
  507. }
  508. if (err == true)
  509. {
  510. parsedPath = null;
  511. }
  512. return parsedPath;
  513. }
  514. /**
  515. * Fatei kopieren
  516. * Code ist ausm netz: http://www.javabeginners.de/Dateien_und_Verzeichnisse/Eine_Datei_kopieren.php
  517. * @param in Eingabefile
  518. * @param out Ausgabefile
  519. * @throws IOException
  520. */
  521. public static void kopierpaste(File in, File out) //throws IOException
  522. {
  523. FileChannel inChannel=null,outChannel=null;
  524. try
  525. {
  526. inChannel = new FileInputStream(in).getChannel();
  527. outChannel = new FileOutputStream(out).getChannel();
  528. inChannel.transferTo(0, inChannel.size(), outChannel);
  529. }
  530. catch (IOException e)
  531. {
  532. e.printStackTrace();
  533. l.error("Kopiererei geerrort");
  534. // throw e;
  535. }
  536. finally
  537. {
  538. if (inChannel != null)
  539. {
  540. try
  541. {
  542. inChannel.close();
  543. }
  544. catch (IOException ex)
  545. {
  546. ex.printStackTrace();
  547. }
  548. }
  549. if (outChannel != null)
  550. {
  551. try
  552. {
  553. outChannel.close();
  554. }
  555. catch (IOException ex)
  556. {
  557. ex.printStackTrace();
  558. }
  559. }
  560. }
  561. }
  562. /**
  563. * Checkt ob pfad nen verzeichnis sit
  564. * @param path welcher pfad
  565. * @return ja/nein
  566. */
  567. public static boolean isDir(String path)
  568. {
  569. return new File(path).isDirectory();
  570. }
  571. /**
  572. * Schrubbt verzeichnis rekursiv raus;
  573. * @param path welches dir
  574. */
  575. public static void verzeichnisKillen(File path)
  576. {
  577. if(path.exists())
  578. {
  579. for (File file : path.listFiles())
  580. {
  581. if (file.isDirectory())
  582. {
  583. verzeichnisKillen(file);
  584. }
  585. file.delete();
  586. }
  587. path.delete();
  588. }
  589. }
  590. public static String fileAsString(String path) throws FileNotFoundException, IOException
  591. {
  592. return fileAsString(new File(path));
  593. }
  594. public static String fileAsString(File path) throws FileNotFoundException, IOException
  595. {
  596. if(path.length()>Integer.MAX_VALUE)
  597. {
  598. throw new IOException(" File too large for specified operation");
  599. }
  600. FileReader fr = new FileReader(path);
  601. CharBuffer c = CharBuffer.allocate((int)path.length());
  602. fr.read(c);
  603. c.rewind();
  604. l.trace(path.length()+"|"+c.length());
  605. return c.toString();
  606. }
  607. }