FileTK.java 18 KB

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