FileTK.java 18 KB

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