0001: /*
0002: * MCS Media Computer Software Copyright (c) 2005 by MCS
0003: * -------------------------------------- Created on 16.01.2004 by w.klaas
0004: *
0005: * Licensed under the Apache License, Version 2.0 (the "License"); you may not
0006: * use this file except in compliance with the License. You may obtain a copy of
0007: * the License at
0008: *
0009: * http://www.apache.org/licenses/LICENSE-2.0
0010: *
0011: * Unless required by applicable law or agreed to in writing, software
0012: * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
0013: * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
0014: * License for the specific language governing permissions and limitations under
0015: * the License.
0016: */
0017: package de.mcs.utils;
0018:
0019: import java.io.BufferedReader;
0020: import java.io.BufferedWriter;
0021: import java.io.File;
0022: import java.io.FileInputStream;
0023: import java.io.FileNotFoundException;
0024: import java.io.FileOutputStream;
0025: import java.io.FileWriter;
0026: import java.io.FilenameFilter;
0027: import java.io.IOException;
0028: import java.io.InputStream;
0029: import java.io.InputStreamReader;
0030: import java.nio.channels.FileChannel;
0031: import java.security.MessageDigest;
0032: import java.security.NoSuchAlgorithmException;
0033: import java.util.ArrayList;
0034: import java.util.regex.Pattern;
0035:
0036: /**
0037: * Die Klasse Files definiert verschiedene statische Hilfsmethoden.
0038: *
0039: * @author w.klaas
0040: */
0041: public final class Files {
0042: /**
0043: * Damit man diese Klasse nicht instanzieren kann.
0044: */
0045: private Files() {
0046: // nothing to do here
0047: }
0048:
0049: /**
0050: * Diese Methode dient der Erzeugung einer temporären Datei in einem
0051: * definierten Verzeichnis.
0052: *
0053: * @param pre
0054: * Prefix der Datei (unter WIN nur 3 Buchstaben möglich)
0055: * @param suf
0056: * Suffix der Datei (Dateiendung)
0057: * @param dir
0058: * Verzeichniss in dem die Datei erzeugt werden soll
0059: * @return Verzeichnis und Dateiname der erzeugten Datei
0060: * @throws IOException
0061: * wenn mal was schief geht
0062: */
0063: public static String getTempFileName(final String pre,
0064: final String suf, final String dir) throws IOException {
0065: String filename;
0066:
0067: File f = File.createTempFile(pre, suf, new File(dir));
0068:
0069: filename = f.getAbsolutePath();
0070:
0071: return filename;
0072: }
0073:
0074: /**
0075: * @return String getting the actual temp path
0076: * @throws IOException
0077: * if something goes wrong
0078: */
0079: public static String getTempPath() throws IOException {
0080: String strTempPath = null;
0081: strTempPath = System.getProperty("java.io.tmpdir");
0082: if (!strTempPath.endsWith(File.separator)) {
0083: return strTempPath + File.separator;
0084: } else {
0085: return strTempPath;
0086: }
0087: // return System.getProperty("java.io.tmpdir") +
0088: // System.getProperty("file.separator");
0089: // File f = File.createTempFile("xxx", ".x");
0090: // f.delete();
0091: // String name = f.getAbsolutePath();
0092: // return name.substring(0, name.lastIndexOf(File.separator) + 1);
0093: }
0094:
0095: /**
0096: * Ersetzung von ungültigen zeichen für den Blobnamen.
0097: *
0098: * @param filename
0099: * Eingangsname
0100: * @return String
0101: */
0102: public static String formatFileNameToBlobName(final String filename) {
0103: String sFilename = filename;
0104: sFilename = sFilename.replaceAll("[^0-9a-zA-Z]", "_");
0105: sFilename = sFilename.replace('.', '_');
0106: return sFilename;
0107: }
0108:
0109: /**
0110: * Von der (vorhandenen) Blobdatei den MD5 berechnen.
0111: *
0112: * @param file
0113: * Dateiname
0114: * @return MD5 String
0115: */
0116: public static String computeMD5FromFile(final String file) {
0117: InputStream in = null;
0118: MessageDigest digest = null;
0119: String s = "";
0120: String sMD5 = "";
0121: // Stream oeffnen
0122: try {
0123: in = new FileInputStream(file);
0124:
0125: // MessageDigest-Objekt fuer MD5 erzeugen
0126: try {
0127: digest = MessageDigest.getInstance("MD5");
0128:
0129: // Puffer
0130: byte[] array = new byte[4096];
0131:
0132: int length = 0;
0133:
0134: // Blockweise lesen und Pruefsumme auffrischen
0135: try {
0136: while (length >= 0) {
0137: length = in.read(array);
0138: if (length > 0) {
0139: digest.update(array, 0, length);
0140: }
0141: }
0142: in.close();
0143:
0144: // Pruefsumme berechnen
0145: byte[] md5 = digest.digest();
0146:
0147: // Pruefsumme als Hex-Zahl ausgeben
0148: for (int l = 0; l < md5.length; l++) {
0149: // System.out.println(md5[l]);
0150: int i;
0151: if (md5[l] > 0) {
0152: i = md5[l];
0153: } else {
0154: i = 256 + md5[l];
0155: }
0156: s = Integer.toHexString(i);
0157: while (s.length() < 2) {
0158: s = "0" + s;
0159: }
0160: sMD5 += s;
0161: }
0162: } catch (IOException e) {
0163: System.err.println("error reading " + file + "("
0164: + e.getMessage() + ")");
0165: }
0166: } catch (NoSuchAlgorithmException e) {
0167: System.err.println("md5 not implemented");
0168: }
0169: } catch (FileNotFoundException e) {
0170: System.err.println("File " + file + " not found");
0171: }
0172: return sMD5;
0173: }
0174:
0175: /**
0176: * A File copy which should be quite fast. If the destination file does not
0177: * exist, it is created.
0178: *
0179: * @param src
0180: * Source file
0181: * @param dest
0182: * Destination file
0183: * @param keepDate
0184: * If <code>true</code> the destination obtains the soruce file
0185: * modification date (like a real file copy does). If If
0186: * <code>true</code> the destination will have the date at the
0187: * time is is copied.
0188: * @throws IOException
0189: * sonst was
0190: */
0191: public static void fileCopy(final File src, final File dest,
0192: final boolean keepDate) throws IOException {
0193:
0194: if (!dest.exists()) {
0195: dest.createNewFile();
0196: }
0197: FileInputStream fin = null;
0198: FileOutputStream fout = null;
0199: FileChannel fchIn = null;
0200: FileChannel fchOut = null;
0201:
0202: try {
0203: fin = new FileInputStream(src);
0204: fout = new FileOutputStream(dest);
0205: fchIn = fin.getChannel();
0206: fchOut = fout.getChannel();
0207:
0208: long position = 0;
0209: long transferred;
0210:
0211: long remaining = fchIn.size();
0212: // it seems, that transferTo "may or may not transfer all of the
0213: // requested bytes",
0214: // so do a loop.
0215:
0216: fchOut.position(0);
0217: fchIn.position(0);
0218:
0219: while (remaining > 0) {
0220: // transferred = fchIn.transferTo(position, remaining, fchOut);
0221: transferred = fchOut.transferFrom(fchIn, position,
0222: remaining);
0223: remaining -= transferred;
0224: position += transferred;
0225: }
0226: } finally {
0227: if (null != fchOut) {
0228: fchOut.close();
0229: }
0230: if (null != fchIn) {
0231: fchIn.close();
0232: }
0233: if (null != fout) {
0234: fout.close();
0235: }
0236: if (null != fin) {
0237: fin.close();
0238: }
0239: }
0240: if (keepDate) {
0241: dest.setLastModified(src.lastModified());
0242: }
0243: }
0244:
0245: /**
0246: * A File copy which should be quite fast. If the destination file does not
0247: * exist, it is created.
0248: *
0249: * @param src
0250: * Source file
0251: * @param dest
0252: * Destination file
0253: * @throws IOException
0254: * geht nicht
0255: */
0256: public static void fileCopy(final File src, final File dest)
0257: throws IOException {
0258:
0259: fileCopy(src, dest, false);
0260:
0261: }
0262:
0263: /**
0264: * getting all files recursivly from a directory.
0265: *
0266: * @param baseDir
0267: * where to search from.
0268: * @param recursive
0269: * search the file structure recursivly.
0270: * @return File[] list of all files
0271: */
0272: public static File[] getFiles(final File baseDir,
0273: final boolean recursive) {
0274: ArrayList<File> fileList = new ArrayList<File>();
0275: File[] files = baseDir.listFiles();
0276: for (int i = 0; i < files.length; i++) {
0277: File file = files[i];
0278: if (file.isDirectory()) {
0279: File[] newFiles = getFiles(file, recursive);
0280: for (int j = 0; j < newFiles.length; j++) {
0281: fileList.add(newFiles[j]);
0282: }
0283: } else if (file.isFile()) {
0284: fileList.add(file);
0285: }
0286: }
0287: return (File[]) fileList.toArray(new File[0]);
0288: }
0289:
0290: /**
0291: * copy a list of list into a directory.
0292: *
0293: * @param files
0294: * list with all files to copy.
0295: * @param installSiteDir
0296: * where to copy to.
0297: * @throws IOException
0298: * if something goes wrong.
0299: */
0300: public static void fileCopy(final File[] files,
0301: final File installSiteDir) throws IOException {
0302: for (int i = 0; i < files.length; i++) {
0303: File srcFile = files[i];
0304: File destFile = new File(installSiteDir, srcFile.getName());
0305: fileCopy(srcFile, destFile);
0306: }
0307: }
0308:
0309: // copied from FileTool class.
0310: /**
0311: * Retrieves the existance of a file or directory (to be or not to be....).
0312: *
0313: * @param fileName
0314: * name of the file or directory.
0315: * @return success
0316: */
0317: public static boolean fileExists(final String fileName) {
0318: return new File(fileName).exists();
0319: }
0320:
0321: /**
0322: * Create a directory; all ancestor directories must exist.
0323: *
0324: * @param directory
0325: * name of the directory
0326: * @return success
0327: */
0328: public static boolean createDirectory(final String directory) {
0329: boolean success = (new File(directory)).mkdir();
0330: if (!success) {
0331: System.err.println("Directory [" + directory
0332: + "] creation failed !");
0333: }
0334: return success;
0335: }
0336:
0337: /**
0338: * Create a directory; all non-existent ancestor directories are.
0339: * automatically created
0340: *
0341: * @param directory
0342: * the directory to create.
0343: * @return success
0344: */
0345: public static boolean createDirectories(final String directory) {
0346: boolean success = (new File(directory)).mkdirs();
0347: if (!success) {
0348: System.err.println("Directory [" + directory
0349: + "] creation failed !");
0350: }
0351: return success;
0352: }
0353:
0354: /**
0355: * Create a directory and a number of subdirectories specified in the String
0356: * array automatically created.
0357: *
0358: * @param aDirectory
0359: * the directory to create.
0360: * @param subdirectories
0361: * array with the subdirectories to create.
0362: * @return success
0363: */
0364: public static boolean createDirectoryStructure(
0365: final String aDirectory, final String[] subdirectories) {
0366: String directory = aDirectory;
0367: boolean success = true;
0368: directory = eliminateDoubleSlashes(directory);
0369: if (!fileExists(directory)) {
0370: if (!createDirectories(directory)) {
0371: return false;
0372: }
0373: }
0374: if (!directory.endsWith("/")) {
0375: directory += '/';
0376: }
0377: for (int iLoop = 0; iLoop < subdirectories.length; iLoop++) {
0378: File subDir = new File(directory + subdirectories[iLoop]);
0379: if (!subDir.exists()) {
0380: if (!createDirectory(directory + subdirectories[iLoop])) {
0381: success = false;
0382: break;
0383: }
0384: }
0385: // success=(iLoop==subdirectories.length-1);
0386: }
0387:
0388: if (!success) {
0389: System.err.println("Directory [" + directory
0390: + "] creation failed !");
0391: }
0392: return success;
0393: }
0394:
0395: /**
0396: * Move / Rename source location to destination. String array automatically
0397: * created
0398: *
0399: * @param source
0400: * source file
0401: * @param destination
0402: * destination file
0403: * @return success
0404: */
0405: public static boolean move(final String source,
0406: final String destination) {
0407: try {
0408: return (new File(source)).renameTo(new File(destination));
0409: } catch (SecurityException e) {
0410: System.err.println("The file " + source
0411: + " could not moved to " + destination + " : "
0412: + e.getLocalizedMessage());
0413: return false;
0414: }
0415: }
0416:
0417: /**
0418: * Copy source location to destination.
0419: *
0420: * @param source
0421: * source file
0422: * @param destination
0423: * destination file
0424: * @return success
0425: */
0426: public static boolean copy(final String source,
0427: final String destination) {
0428: searchDepth = 0;
0429: return filecopy(source, destination, true);
0430: }
0431:
0432: /**
0433: * Copy source location to destination.
0434: *
0435: * @param source
0436: * source file
0437: * @param destination
0438: * destination file
0439: * @param subdirectories
0440: * <code>true</code> if subdirectories should be copied too,
0441: * otherwise <code>false</code>
0442: * @return success
0443: */
0444: public static boolean copy(final String source,
0445: final String destination, final boolean subdirectories) {
0446: searchDepth = 0;
0447: return filecopy(source, destination, subdirectories);
0448: }
0449:
0450: /**
0451: * Filename filter class. This class will determine files with dos
0452: * wildcards.
0453: *
0454: * @author w.klaas
0455: */
0456: static class FileIncludes implements FilenameFilter {
0457:
0458: /** directory to eveluate. */
0459: private File dir;
0460:
0461: /** the regex. */
0462: private Pattern mask;
0463:
0464: /** prevent instancing with the default constructor. */
0465: private FileIncludes() {
0466: throw new UnsupportedOperationException();
0467: }
0468:
0469: /**
0470: * is the mask a mask?
0471: *
0472: * @param mask
0473: * the mask
0474: *
0475: * @return <code>true</code> if the mask containing a * or ?
0476: */
0477: private static boolean isMask(final String mask) {
0478: int pos = mask.indexOf('*');
0479: if (pos < 0) {
0480: pos = mask.indexOf('?');
0481: }
0482: return pos >= 0;
0483: }
0484:
0485: /**
0486: * special regexp chars : '.', '\\', '$', '^', '(' , ')', '[', ']' ,'+', .
0487: * (must be masked if in mask) special mask chars to convert for regexp :
0488: * '*' -> '.*', '?' -> '.+'
0489: */
0490: private static String regexpSpecChars = ".\\$^()[]+";
0491:
0492: /**
0493: * convert the mask to a regualr expression.
0494: *
0495: * @param aMask
0496: * the mask
0497: * @return String regular expression.
0498: */
0499: String toRegExp(final String aMask) {
0500: StringBuffer sb = new StringBuffer();
0501: int length = aMask.length();
0502: for (int index = 0; index < length; index++) {
0503: char ch = aMask.charAt(index);
0504: if (ch == '*') {
0505: sb.append(".*");
0506: } else if (ch == '?') {
0507: sb.append(".+");
0508: } else if (regexpSpecChars.indexOf(ch) >= 0) {
0509: sb.append('\\').append(ch);
0510: } else {
0511: sb.append(ch);
0512: }
0513: }
0514: return sb.toString();
0515: }
0516:
0517: /**
0518: * Constructs a FilenameFilter instance to filter files, which base name
0519: * (without the directoy path) that match the given regular expression.
0520: *
0521: * @param aDir
0522: * the directory
0523: * @param aMask
0524: * the mask
0525: * @throws java.util.regex.PatternSyntaxException
0526: */
0527: public FileIncludes(final File aDir, final String aMask) {
0528: this .dir = aDir;
0529: this .mask = Pattern.compile(toRegExp(aMask));
0530: // System.out.println("FileIncludes: dir=" + dir.toString() + ",
0531: // mask=" + mask);
0532:
0533: }
0534:
0535: /**
0536: * Tests if a specified file should be included in a file list.
0537: *
0538: * @param aDir
0539: * the directory in which the file was found.
0540: * @param name
0541: * the name of the file.
0542: * @return <code>true</code> if and only if the name should be
0543: * included in the file list; <code>false</code> otherwise.
0544: * @see java.io.FilenameFilter#accept(java.io.File, java.lang.String)
0545: */
0546: public boolean accept(final File aDir, final String name) {
0547: // System.out.println("accept: dir=" + dir.toString() + ", name=" +
0548: // name);
0549: if (aDir.equals(this .dir)) {
0550: boolean matches = mask.matcher(name).matches();
0551: // System.out.println("accept: result=" + matches);
0552: return matches;
0553: } else {
0554: // System.out.println("accept: result=" + false);
0555: return false;
0556: }
0557: }
0558:
0559: }
0560:
0561: /** default subdirectory depth to copy. */
0562: private static int searchDepth = 0;
0563:
0564: /**
0565: * Copy source location to destination.
0566: *
0567: * @param source
0568: * The pathname of a single directory or a single file or
0569: * multiple files through a filemask.
0570: * @param destination
0571: * destination path
0572: * @param subdirectories
0573: * allow subdirectories to be copied
0574: * @return <code>true</code> if this operation succseeded
0575: */
0576: protected static boolean filecopy(final String source,
0577: final String destination, final boolean subdirectories) {
0578:
0579: boolean success = true; // just be optimistic
0580: File sourceFile = new File(source);
0581: if (sourceFile.isDirectory()) {
0582: if (searchDepth++ > 0 && !subdirectories) {
0583: return true;
0584: }
0585: if (!fileExists(destination)) {
0586: createDirectories(destination);
0587: }
0588: String[] subFiles = sourceFile.list();
0589: for (int iLoop = 0; iLoop < subFiles.length; iLoop++) {
0590: filecopy(source + File.separator + subFiles[iLoop],
0591: destination + File.separator + subFiles[iLoop],
0592: subdirectories);
0593: }
0594: } else {
0595: // create destination directory if it does not exist
0596: int fSlash = destination.lastIndexOf("/"), bSlash = destination
0597: .lastIndexOf("\\");
0598: int slash;
0599: if (fSlash > bSlash) {
0600: slash = fSlash;
0601: } else {
0602: slash = bSlash;
0603: }
0604: if (slash > -1) {
0605: String path = destination.substring(0, slash);
0606: File dest = new File(path);
0607: if (!dest.exists()) {
0608: createDirectories(path);
0609: }
0610: }
0611:
0612: File[] inputFiles = new File[] { sourceFile };
0613: String mask = sourceFile.getName();
0614: if (FileIncludes.isMask(mask)) {
0615: File sourceDir = sourceFile.getParentFile();
0616: if (null != sourceDir && mask.length() > 0) {
0617: try {
0618: FilenameFilter filter = new FileIncludes(
0619: sourceDir, mask);
0620: inputFiles = sourceDir.listFiles(filter);
0621: } catch (java.util.regex.PatternSyntaxException e) {
0622: // nothing to do here
0623: }
0624: }
0625: }
0626:
0627: File destFile = new File(destination);
0628: if (null != inputFiles) {
0629: if (destFile.isFile() && inputFiles.length > 1) {
0630: System.err
0631: .println("For copying multiple files to the destination \""
0632: + destination
0633: + "\" it must be a directory and NOT A SINGLE file.");
0634: success = false;
0635: } else {
0636: for (int idx = 0; idx < inputFiles.length; idx++) {
0637: File inputFile = inputFiles[idx];
0638:
0639: File destinationFile;
0640: if (destFile.isDirectory()) {
0641: destinationFile = new File(destFile,
0642: inputFile.getName());
0643: } else {
0644: destinationFile = destFile;
0645: }
0646:
0647: try {
0648: // calling filecopy using FileChannel
0649: Files.fileCopy(inputFile, destinationFile,
0650: true);
0651: success = true;
0652: } catch (FileNotFoundException eFNF) {
0653: System.err
0654: .println("The source file could not be found. "
0655: + eFNF);
0656: System.err.println("Tried to copy "
0657: + inputFile + " to "
0658: + destinationFile + " : " + eFNF);
0659: success = false;
0660: break;
0661: } catch (IOException eIO) {
0662: System.err
0663: .println("IOException occured while copying file.");
0664: System.err.println("Tried to copy "
0665: + inputFile + " to "
0666: + destinationFile + " : " + eIO);
0667: success = false;
0668: break;
0669: }
0670: }
0671: }
0672: }
0673: }
0674: return success;
0675: }
0676:
0677: /**
0678: * @param filename
0679: * A filename that may be a relative filename like "." or "..".
0680: * @return The absolute <code>File</code> name instance fo the given
0681: * (relative) filename. Return <code>null</code> if ".." is given
0682: * and the current or parent directory is /
0683: */
0684: public static File getAbsoluteFile(final String filename) {
0685: File file = new File(filename).getAbsoluteFile();
0686: if (".".equals(file.getName())) {
0687: file = file.getParentFile();
0688: } else if ("..".equals(file.getName())) {
0689: file = file.getParentFile();
0690: if (null != file) {
0691: file = file.getParentFile();
0692: }
0693: }
0694: return file;
0695: }
0696:
0697: /**
0698: * making a string to a directory with ending on File.separator.
0699: *
0700: * @param aPath
0701: * path to convert
0702: * @return string
0703: */
0704: public static String makeDirectory(final String aPath) {
0705: String path = aPath;
0706: String separatorChar = System.getProperty("file.separator");
0707: if (path != null && !path.endsWith(separatorChar)) {
0708: path += separatorChar;
0709: }
0710: return path;
0711: }
0712:
0713: /**
0714: * removes a directory recursively. All Files and Subdirectories are
0715: * removed. If bRecursive is false and the directory is not empty, an
0716: * IOException is thrown.
0717: *
0718: * @param filename
0719: * path or file to remove
0720: * @param bRecursive
0721: * delete all subfolders too
0722: * @return success <code>true</code> if all files could be removed, else
0723: * return <code>false</code>
0724: * @throws IOException
0725: * if something goes wrong
0726: */
0727: public static boolean remove(final String filename,
0728: final boolean bRecursive) throws IOException {
0729: return remove(filename, bRecursive, null);
0730: }
0731:
0732: /**
0733: * removes a directory recursively. All Files and Subdirectories are
0734: * removed. If bRecursive is false and the directory is not empty, an
0735: * IOException is thrown.
0736: *
0737: * @param filename
0738: * path or file to remove
0739: * @param bRecursive
0740: * delete all subfolders too
0741: * @param excludes
0742: * list with files to exclude from deleting
0743: * @return success <code>true</code> if all files could be removed, else
0744: * return <code>false</code>
0745: * @throws IOException
0746: * if something goes wrong
0747: */
0748: public static boolean remove(final String filename,
0749: final boolean bRecursive, final ArrayList excludes)
0750: throws IOException {
0751: boolean bSuccess = true;
0752: if (filename != null && 0 != filename.length()) {
0753: File file = new File(filename);
0754: if (file.isDirectory()) {
0755: String[] files = file.list();
0756:
0757: if (!bRecursive && files.length > 0) {
0758: System.err.println();
0759: throw new IOException("Directory "
0760: + file.getAbsolutePath() + " is not Empty");
0761: } else {
0762: for (int iLoop = 0; iLoop < files.length; iLoop++) {
0763: String toRemove = convertSlashes(file
0764: .getAbsolutePath()
0765: + "/" + files[iLoop]);
0766: if (!isExcluded(toRemove, excludes)) {
0767: if (!remove(toRemove, true)) {
0768: bSuccess = false;
0769: }
0770: }
0771: }
0772: if (bSuccess) {
0773: if (!isExcluded(filename, excludes)) {
0774: bSuccess = remove(filename);
0775: }
0776: }
0777: }
0778: } else {
0779: if (!isExcluded(filename, excludes)) {
0780: bSuccess = remove(filename);
0781: }
0782: }
0783: }
0784: return bSuccess;
0785: }
0786:
0787: /**
0788: * checks if a file is in the exclude list.
0789: *
0790: * @param filename
0791: * file to test
0792: * @param excludes
0793: * list with the excluded files
0794: * @return boolean <code>true</code> if the file is in the excludelist,
0795: * else <code>false</code>
0796: */
0797: private static boolean isExcluded(final String filename,
0798: final ArrayList excludes) {
0799: boolean bDelete = true;
0800: if (excludes != null && excludes.size() > 0) {
0801: for (int iFileLoop = 0; iFileLoop < excludes.size(); iFileLoop++) {
0802: String exclude = convertSlashes((String) excludes
0803: .get(iFileLoop));
0804: if (filename.indexOf(exclude) > -1
0805: || exclude.startsWith(filename)) {
0806: bDelete = false;
0807: break;
0808: }
0809: }
0810: }
0811: return !bDelete;
0812: }
0813:
0814: /**
0815: * Delete the file.
0816: *
0817: * @param filename
0818: * file to delete
0819: * @return <code>true</code> if the file could be delete,
0820: * <code>false</code> if not.
0821: */
0822: public static boolean remove(final String filename) {
0823: try {
0824: return new File(filename).delete();
0825: } catch (SecurityException e) {
0826: System.err.println("The file " + filename
0827: + " could not be removed: "
0828: + e.getLocalizedMessage());
0829: return false;
0830: }
0831: }
0832:
0833: /**
0834: * reading a file into an arraylist. Every line is one entry.
0835: *
0836: * @param fileName
0837: * file to read
0838: * @return ArrayList with all lines
0839: */
0840: public static ArrayList readFileToArrayList(final String fileName) {
0841: ArrayList<String> list = new ArrayList<String>();
0842: BufferedReader br = null;
0843: try {
0844: br = new BufferedReader(new InputStreamReader(
0845: new FileInputStream(fileName)));
0846: } catch (FileNotFoundException e) {
0847: System.err.println("The File " + fileName
0848: + " could not be found !!");
0849: e.printStackTrace();
0850: System.exit(3);
0851: }
0852: String line = "";
0853: try {
0854: while ((line = br.readLine()) != null) {
0855: if (line.trim().length() > 0
0856: && line.trim().charAt(0) != '#') {
0857: list.add(line);
0858: }
0859: }
0860: } catch (IOException e1) {
0861: System.err.println("IOException occured while reading "
0862: + fileName + "");
0863: e1.printStackTrace();
0864: } finally {
0865: try {
0866: br.close();
0867: } catch (IOException e) {
0868: e.printStackTrace();
0869: }
0870: }
0871: return list;
0872: }
0873:
0874: /**
0875: * reading a file into an string.
0876: *
0877: * @param fileName
0878: * file to read
0879: * @return ArrayList with all lines
0880: */
0881: public static String readFileToString(final String fileName) {
0882: StringBuffer buffer = new StringBuffer();
0883: BufferedReader br = null;
0884: try {
0885: br = new BufferedReader(new InputStreamReader(
0886: new FileInputStream(fileName)));
0887: } catch (FileNotFoundException e) {
0888: System.err.println("The File " + fileName
0889: + " could not be found !!");
0890: e.printStackTrace();
0891: System.exit(3);
0892: }
0893: String line = "";
0894: try {
0895: while ((line = br.readLine()) != null) {
0896: if (line.trim().length() > 0) {
0897: buffer.append(line);
0898: buffer.append("\r\n");
0899: }
0900: }
0901: } catch (IOException e1) {
0902: System.err.println("IOException occured while reading "
0903: + fileName + "");
0904: e1.printStackTrace();
0905: } finally {
0906: try {
0907: br.close();
0908: } catch (IOException e) {
0909: e.printStackTrace();
0910: }
0911: }
0912: return buffer.toString();
0913: }
0914:
0915: /**
0916: * simple writing a string into a file.
0917: *
0918: * @param filename
0919: * of the file to create
0920: * @param content
0921: * string to write into the file.
0922: */
0923: public static void writeStringToFile(final String filename,
0924: final String content) {
0925: File file = new File(filename);
0926: try {
0927: BufferedWriter bufWriter = new BufferedWriter(
0928: new FileWriter(file));
0929: bufWriter.write(content);
0930: bufWriter.close();
0931: } catch (IOException e) {
0932: // TODO Auto-generated catch block
0933: e.printStackTrace();
0934: }
0935: }
0936:
0937: /**
0938: * Eleminates // in a filename.
0939: *
0940: * @param filename
0941: * to convert
0942: * @return String
0943: */
0944: public static String eliminateDoubleSlashes(final String filename) {
0945: String result = "";
0946: if (filename.indexOf(":") == -1 && filename.startsWith("//")) {
0947: result = filename.substring(0, 2)
0948: + filename.substring(2).replaceAll("//", "/");
0949: } else {
0950: result = filename.replaceAll("//", "/");
0951: }
0952: return result;
0953: }
0954:
0955: /**
0956: * converts 2 backslashes into one slash.
0957: *
0958: * @param path
0959: * to convert
0960: * @return string
0961: */
0962: public static String convertSlashes(final String path) {
0963: return path.replaceAll("\\\\", "/");
0964: }
0965:
0966: /**
0967: * converts one slash into 2 backslashes.
0968: *
0969: * @param path
0970: * to convert
0971: * @return string
0972: */
0973: public static String convertBackSlashes(final String path) {
0974: return path.replaceAll("/", "\\\\");
0975: }
0976:
0977: /**
0978: * converts only if backslash is not proceeded by a blank.
0979: *
0980: * @param aPath
0981: * to convert
0982: * @return string
0983: */
0984: public static String convertBackSlashesNoParams(final String aPath) {
0985: String path = aPath;
0986: int slash = -1;
0987: while ((slash = path.indexOf("/", slash + 1)) > -1) {
0988: if (slash > -1 && path.charAt(slash - 1) != ' ') {
0989: String sLineStart = path.substring(0, slash);
0990: String sLineEnd = path.substring(slash + 1);
0991: path = sLineStart + "\\" + sLineEnd;
0992: }
0993: }
0994: return path;
0995: }
0996:
0997: /**
0998: * converting the given path with an File.separator at the end.
0999: *
1000: * @param aPath
1001: * the path to convert
1002: * @return the converted path
1003: */
1004: public static String normPath(final String aPath) {
1005: if (!aPath.endsWith("/") && !aPath.endsWith("\\")) {
1006: return aPath + File.separator;
1007: } else {
1008: return aPath;
1009: }
1010: }
1011:
1012: /**
1013: * getting the file extension.
1014: *
1015: * @param file
1016: * the file to get the extension from.
1017: * @return the extension with "." or <code>null</code> if the file is not
1018: * a file.
1019: */
1020: public static String getExtension(final File file) {
1021: if (file.isFile()) {
1022: String name = file.getName();
1023: return name.substring(name.lastIndexOf("."));
1024: }
1025: return null;
1026: }
1027:
1028: /**
1029: * getting the file extension.
1030: *
1031: * @param file
1032: * the file to get the extension from.
1033: * @return the extension with "." or <code>null</code> if the file is not
1034: * a file.
1035: */
1036: public static String extractName(final File file) {
1037: if (file.isFile()) {
1038: String name = file.getName();
1039: return name.substring(1, name.lastIndexOf("."));
1040: }
1041: return null;
1042: }
1043: }
|