Example usage for java.io File toString

List of usage examples for java.io File toString

Introduction

In this page you can find the example usage for java.io File toString.

Prototype

public String toString() 

Source Link

Document

Returns the pathname string of this abstract pathname.

Usage

From source file:com.buaa.cfs.utils.FileUtil.java

/**
 * Given a Tar File as input it will untar the file in a the untar directory passed as the second parameter
 * <p>//from  w w  w  .  j a v  a 2s .co  m
 * This utility will untar ".tar" files and ".tar.gz","tgz" files.
 *
 * @param inFile   The tar file as input.
 * @param untarDir The untar directory where to untar the tar file.
 *
 * @throws IOException
 */
public static void unTar(File inFile, File untarDir) throws IOException {
    if (!untarDir.mkdirs()) {
        if (!untarDir.isDirectory()) {
            throw new IOException("Mkdirs failed to create " + untarDir);
        }
    }

    boolean gzipped = inFile.toString().endsWith("gz");
    if (Shell.WINDOWS) {
        // Tar is not native to Windows. Use simple Java based implementation for
        // tests and simple tar archives
        unTarUsingJava(inFile, untarDir, gzipped);
    } else {
        // spawn tar utility to untar archive for full fledged unix behavior such
        // as resolving symlinks in tar archives
        unTarUsingTar(inFile, untarDir, gzipped);
    }
}

From source file:PSOResultFileReader.java

/**
 * Constructs a result file reader for reading the approximation sets from
 * the specified result file./*from www  . ja va  2s . co  m*/
 * 
 * @param problem the problem
 * @param file the file containing the results
 * @throws IOException if an I/O error occurred
 */
public PSOResultFileReader(Problem problem, File file) throws IOException {
    super();
    this.problem = problem;

    System.out.println("Reading file: " + file.toString());

    reader = new BufferedReader(new FileReader(file));

    // prime the reader by reading the first line
    line = reader.readLine();
}

From source file:com.CodeSeance.JSeance2.CodeGenXML.XMLElements.Test.OutputTest.java

@Test
public void fileOutputTest_AutoCreateParentDirs() {
    CleanupAutoCreateParentDirs();//from   w w  w.  jav a 2s.  c o  m

    try {
        File outputFile = new File(
                "A" + File.separator + "B" + File.separator + "C" + File.separator + "Output.txt");
        template.append(String.format("!Output(\"%s\")!",
                org.apache.commons.lang.StringEscapeUtils.escapeJavaScript(outputFile.toString())));
        template.append("Test");
        template.append("!End!");
        expectResult("", false, false);

        File fullPath = new File(System.getProperty("java.io.tmpdir") + File.separator + outputFile.toString());
        String outcome = convertFileToString(fullPath, "UTF-8");

        if (!"Test".equals(outcome)) {
            throw new RuntimeException("Test Failed: Was expecting:[Test] and obtained:[" + outcome + "]");
        }
        reset();
    } finally {
        CleanupAutoCreateParentDirs();
    }
}

From source file:info.dolezel.fatrat.plugins.helpers.JarClassLoader.java

private Set<Class> findClasses(File directory, String packageName, Class annotation)
        throws ClassNotFoundException, IOException {
    Set<Class> classes = new HashSet<Class>();
    if (!directory.exists()) {

        String fullPath = directory.toString();
        String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
        JarFile jarFile = new JarFile(jarPath);
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            String entryName = entry.getName();
            if (entryName.endsWith(".class") && !entryName.contains("$")) {
                String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", "");
                Class cls = this.loadClass(className);

                if (annotation == null || cls.isAnnotationPresent(annotation))
                    classes.add(cls);/*w  w w .j av a 2  s.  co  m*/
            }
        }
    } else {
        File[] files = directory.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                assert !file.getName().contains(".");
                classes.addAll(findClasses(file, packageName + "." + file.getName(), annotation));
            } else if (file.getName().endsWith(".class")) {
                Class cls = this.loadClass(
                        packageName + '.' + file.getName().substring(0, file.getName().length() - 6));

                if (annotation == null || cls.isAnnotationPresent(annotation))
                    classes.add(cls);
            }
        }
    }
    return classes;
}

From source file:com.blackducksoftware.tools.vuln_collector.VCProcessor.java

/**
 * Creates a directory using the project name Parses the name to escape
 * offensive characters.//from w  w  w .  j  av  a 2s  .  c  o  m
 * 
 * @param reportLocation
 * @param project
 * @return
 * @throws Exception
 */
private File prepareSubDirectory(File reportLocation, String project) throws Exception {
    project = formatProjectPath(project);
    File reportLocationSubDir = new File(reportLocation.toString() + File.separator + project);
    if (!reportLocationSubDir.exists()) {
        boolean dirsMade = reportLocationSubDir.mkdirs();
        if (!dirsMade) {
            throw new Exception("Unable to create report sub-directory for project: " + project);
        }
    }

    // Copy the web resources into this new location
    ClassLoader classLoader = getClass().getClassLoader();
    File webresources = new File(classLoader.getResource(WEB_RESOURCE).getFile());

    if (!webresources.exists()) {
        throw new Exception("Fatal exception, internal web resources are missing!");
    }

    File[] webSubDirs = webresources.listFiles();
    if (webSubDirs.length == 0) {
        throw new Exception(
                "Fatal exception, internal web resources sub directories are missing!  Corrupt archive.");
    }

    boolean readable = webresources.setReadable(true);
    if (!readable) {
        throw new Exception("Fatal. Cannot read internal web resource directory!");
    }

    try {
        for (File webSubDir : webSubDirs) {
            if (webSubDir.isDirectory()) {
                FileUtils.copyDirectoryToDirectory(webSubDir, reportLocationSubDir);
            } else {
                FileUtils.copyFileToDirectory(webSubDir, reportLocationSubDir);
            }
        }
    } catch (IOException ioe) {
        throw new Exception("Error during creation of report directory", ioe);
    }

    return reportLocationSubDir;
}

From source file:me.philnate.textmanager.utils.PDFCreator.java

@SuppressWarnings("deprecation")
private void preparePDF() {
    try {//from w  w  w  .  j  a  v  a  2  s.  c o  m
        File path = new File(SystemUtils.getUserDir(), "template");
        File template = new File(path, Setting.find("template").getValue());

        Velocity.setProperty("file.resource.loader.path", path.getAbsolutePath());
        Velocity.init();
        VelocityContext ctx = new VelocityContext();

        // User data/Settings
        for (Setting setting : ds.find(Setting.class).asList()) {
            ctx.put(setting.getKey(), setting.getValue());
        }

        NumberFormat format = NumberFormat.getNumberInstance(new Locale(Setting.find("locale").getValue()));
        // #60 always show 2 digits for fraction no matter if right most(s)
        // are zero
        format.setMinimumFractionDigits(2);
        format.setMaximumFractionDigits(2);
        ctx.put("number", format);
        // TODO update schema to have separate first and lastname
        // Customer data
        ctx.put("customer", customer);

        // General data
        ctx.put("month", new DateFormatSymbols().getMonths()[month]);
        ctx.put("math", new MathTool());
        // Billing data
        ctx.put("allItems", BillingItem.find(customer.getId(), year, month));
        ctx.put("billNo", bill.getBillNo());

        StringWriter writer = new StringWriter();
        Velocity.mergeTemplate(template.getName(), ctx, writer);
        File filledTemplate = new File(path, bill.getBillNo() + ".tex");
        FileUtils.writeStringToFile(filledTemplate, writer.toString(), "ISO-8859-1");

        ProcessBuilder pdfLatex = new ProcessBuilder(Setting.find("pdfLatex").getValue(),
                "-interaction nonstopmode", "-output-format pdf", filledTemplate.toString());

        // Saving template file (just in case it may be needed later
        GridFSFile texFile = tex.createFile(filledTemplate);
        texFile.put("month", month);
        texFile.put("year", year);
        texFile.put("customerId", customer.getId());
        texFile.save();

        pdfLatex.directory(path);
        String pdfPath = filledTemplate.toString().replaceAll("tex$", "pdf");
        if (0 == printOutputStream(pdfLatex)) {
            // display Bill in DocumentViewer
            new ProcessBuilder(Setting.find("pdfViewer").getValue(), pdfPath).start().waitFor();
            GridFSFile pdfFile = pdf.createFile(new File(pdfPath));
            pdfFile.put("month", month);
            pdfFile.put("year", year);
            pdfFile.put("customerId", customer.getId());
            pdf.remove(QueryBuilder.start("month").is(month).and("year").is(year).and("customerId")
                    .is(customer.getId()).get());
            pdfFile.save();
            File[] files = path.listFiles((FileFilter) new WildcardFileFilter(bill.getBillNo() + ".*"));
            for (File file : files) {
                FileUtils.forceDelete(file);
            }
        } else {
            new JOptionPane(
                    "Bei der Erstellung der Rechnung ist ein Fehler aufgetreten. Es wurde keine Rechnung erstellt.\n Bitte Schauen sie in die Logdatei fr nhere Fehlerinformationen.",
                    JOptionPane.ERROR_MESSAGE).setVisible(true);
        }
    } catch (IOException e) {
        Throwables.propagate(e);
    } catch (InterruptedException e) {
        Throwables.propagate(e);
    }
}

From source file:eu.stratosphere.core.fs.local.LocalFileSystem.java

@Override
public boolean delete(final Path f, final boolean recursive) throws IOException {

    final File file = pathToFile(f);
    if (file.isFile()) {
        return file.delete();
    } else if ((!recursive) && file.isDirectory() && (file.listFiles().length != 0)) {
        throw new IOException("Directory " + file.toString() + " is not empty");
    }//from   ww  w.  j a v  a 2 s  .  c  o  m

    return delete(file);
}

From source file:com.exercise.AndroidClient.RecvFrom.java

private Uri getDestFileUri() throws IOException {

    // map "music" to Environment.DIRECTORY_MUSIC 
    String destDir = destDirTypes.get(destinationType);
    if (destDir == null)
        throw new IllegalArgumentException("Invalid destination dir type : " + destinationType);

    // get the public 'standard directory', ie Download, Music etc
    File dir = Environment.getExternalStoragePublicDirectory(destDir);

    // add any subdir asked by caller & create dir struct upto the subdir if required
    dir = new File(dir, subDir);
    if (!dir.exists() || !dir.isDirectory()) {
        if (!dir.mkdirs())
            throw new IOException("Failed to create directories : " + dir.toString());
    }/* w  ww. j a  v a2 s . c  om*/

    // the full path to the file
    File path = new File(dir, filename);
    return Uri.fromFile(path);
}

From source file:com.microsoft.azure.management.datalake.store.uploader.DataLakeStoreUploader.java

/**
 * Verifies that the metadata is consistent with the local file information.
 *
 * @param metadata The {@link UploadMetadata} to check against a serialized copy.
 * @throws OperationsException//from w  ww.j a  v  a2s.  c  o  m
 */
private void validateMetadataMatchesLocalFile(UploadMetadata metadata) throws OperationsException {
    if (!metadata.getTargetStreamPath().trim()
            .equalsIgnoreCase(this.getParameters().getTargetStreamPath().trim())) {
        throw new OperationsException("Metadata points to a different target stream than the input parameters");
    }

    //verify that it matches against local file (size, name)
    File metadataInputFileInfo = new File(metadata.getInputFilePath());
    File paramInputFileInfo = new File(this.getParameters().getInputFilePath());

    if (!paramInputFileInfo.toString().toLowerCase().equals(metadataInputFileInfo.toString().toLowerCase())) {
        throw new OperationsException("The metadata refers to different file than the one requested");
    }

    if (!metadataInputFileInfo.exists()) {
        throw new OperationsException("The metadata refers to a file that does not exist");
    }

    if (metadata.getFileLength() != metadataInputFileInfo.length()) {
        throw new OperationsException("The metadata's file information differs from the actual file");
    }
}

From source file:com.vtls.opensource.jhove.JHOVEDocumentFactory.java

/**
 * Get a JHOVE Document from a {@link File}
 * @param file  a resource {@link File}/*from  w w  w .  ja  v  a  2s  .co m*/
 * @return a JDOM Document
 * @throws IOException 
 * @throws JDOMException 
 */
public Document getDocument(File file) throws IOException, JDOMException {
    // Create the RepInfo instance.
    RepInfo representation = new RepInfo(file.toString());
    if (!file.exists()) {
        representation.setMessage(new ErrorMessage("Content not found."));
        representation.setWellFormed(RepInfo.FALSE);
    } else if (!file.isFile() || !file.canRead()) {
        representation.setMessage(new ErrorMessage("Content cannot be read."));
        representation.setWellFormed(RepInfo.FALSE);
    } else {
        representation.setSize(file.length());
        representation.setLastModified(new Date(file.lastModified()));
        populateRepresentation(representation, file);
    }
    return getDocumentFromRepresentation(representation);
}