Example usage for java.io File getCanonicalPath

List of usage examples for java.io File getCanonicalPath

Introduction

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

Prototype

public String getCanonicalPath() throws IOException 

Source Link

Document

Returns the canonical pathname string of this abstract pathname.

Usage

From source file:edu.buffalo.cse.pigout.Main.java

public static String validateLogFile(String logFileName, String scriptName) {
    String strippedDownScriptName = null;

    // script name
    if (scriptName != null) {
        File scriptFile = new File(scriptName);
        if (!scriptFile.isDirectory()) {
            String scriptFileAbsPath;
            try {
                scriptFileAbsPath = scriptFile.getCanonicalPath();
                strippedDownScriptName = getFileFromCanonicalPath(scriptFileAbsPath);
            } catch (IOException ioe) {
                log.warn("Could not compute canonical path to the script file " + ioe.getMessage());
                strippedDownScriptName = null;
            }/*from  w w w. j ava 2s  . c  o  m*/
        }
    }

    String defaultLogFileName = (strippedDownScriptName == null ? "pigout_" : strippedDownScriptName)
            + new Date().getTime() + ".log";
    File logFile;

    if (logFileName != null) {
        logFile = new File(logFileName);

        //Check if the file name is a directory
        //append the default file name to the file
        if (logFile.isDirectory()) {
            if (logFile.canWrite()) {
                try {
                    logFileName = logFile.getCanonicalPath() + File.separator + defaultLogFileName;
                } catch (IOException ioe) {
                    log.warn("Could not compute canonical path to the log file " + ioe.getMessage());
                    return null;
                }
                return logFileName;
            } else {
                log.warn("Need write permission in the directory: " + logFileName + " to create log file.");
                return null;
            }
        } else {
            //we have a relative path or an absolute path to the log file
            //check if we can write to the directory where this file is/will be stored
            if (logFile.exists()) {
                if (logFile.canWrite()) {
                    try {
                        logFileName = new File(logFileName).getCanonicalPath();
                    } catch (IOException ioe) {
                        log.warn("Could not compute canonical path to the log file " + ioe.getMessage());
                        return null;
                    }
                    return logFileName;
                } else {
                    //do not have write permissions for the log file
                    //bail out with an error message
                    log.warn("Cannot write to file: " + logFileName + ". Need write permission.");
                    return logFileName;
                }
            } else {
                logFile = logFile.getParentFile();

                if (logFile != null) {
                    //if the directory is writable we are good to go
                    if (logFile.canWrite()) {
                        try {
                            logFileName = new File(logFileName).getCanonicalPath();
                        } catch (IOException ioe) {
                            log.warn("Could not compute canonical path to the log file " + ioe.getMessage());
                            return null;
                        }
                        return logFileName;
                    } else {
                        log.warn("Need write permission in the directory: " + logFile + " to create log file.");
                        return logFileName;
                    }
                } //end if logFile != null else is the default in fall through
            } //end else part of logFile.exists()
        } //end else part of logFile.isDirectory()
    } //end if logFileName != null

    //file name is null or its in the current working directory
    //revert to the current working directory
    String currDir = System.getProperty("user.dir");
    logFile = new File(currDir);
    logFileName = currDir + File.separator + (logFileName == null ? defaultLogFileName : logFileName);
    if (logFile.canWrite()) {
        return logFileName;
    }
    log.warn("Cannot write to log file: " + logFileName);
    return null;
}

From source file:com.thebuzzmedia.exiftool.ExifToolNew3.java

public static String getAbsolutePath(File file) throws IOException {
    String path = file.getAbsolutePath();
    if (file.exists() == false)
        file = new File(path);
    path = file.getCanonicalPath();
    if (file.isDirectory() && (path.endsWith(File.separator) == false))
        path += File.separator;//w w w.  j a  va 2 s  . c  o m
    return path;
}

From source file:com.frostwire.android.LollipopFileSystem.java

private static String getExtSdCardFolder(Context context, File file) {
    if (file.getAbsolutePath().contains("/Android/data/")) {
        return null;
    }// ww w .j  a v  a  2 s. c  o  m

    String[] extSdPaths = getExtSdCardPaths(context);
    try {
        for (String extSdPath : extSdPaths) {
            if (file.getCanonicalPath().startsWith(extSdPath)) {
                return extSdPath;
            }
        }
    } catch (IOException e) {
        return null;
    }
    return null;
}

From source file:com.springsource.open.jms.SharedDatabaseApplication.java

@PostConstruct
public void init() throws IOException {
    File directory = new File("derby-home");
    System.setProperty("derby.system.home", directory.getCanonicalPath());
}

From source file:net.sf.webphotos.tools.Thumbnail.java

/**
 * Cria thumbs para as imagens. Testa se j existem valores setados para o
 * thumb, se no existir chama o mtodo/*ww w.j a  va  2s .c om*/
 * {@link net.sf.webphotos.Thumbnail#inicializar() inicializar} para setar
 * seus valores. Abre o arquivo de imagem passado como parmetro e checa se
 *  uma foto vlida. Obtm o tamanho original da imagem, checa se est no
 * formato paisagem ou retrato e utiliza o mtodo
 * {@link java.awt.Image#getScaledInstance(int,int,int) getScaledInstance}
 * para calcular os thumbs. Ao final, salva as imagens.
 *
 * @param caminhoCompletoImagem Caminho da imagem.
 */
public static void makeThumbs(String caminhoCompletoImagem) {

    String diretorio, arquivo;
    if (t1 == 0) {
        inicializar();
    }

    try {
        File f = new File(caminhoCompletoImagem);
        if (!f.isFile() || !f.canRead()) {
            Util.err.println("[Thumbnail.makeThumbs]/ERRO: Erro no caminho do arquivo " + caminhoCompletoImagem
                    + " incorreto");
            return;
        }

        // Foto em alta corrompida 
        if (getFormatName(f) == null) {
            Util.err.println("[Thumbnail.makeThumbs]/ERRO: Foto Corrompida");
            return;
        } else {
            Util.out.println("[Thumbnail.makeThumbs]/INFO: Foto Ok!");
        }

        diretorio = f.getParent();
        arquivo = f.getName();

        ImageIcon ii = new ImageIcon(f.getCanonicalPath());
        Image i = ii.getImage();

        Image tumb1, tumb2, tumb3, tumb4;

        // obtm o tamanho da imagem original
        int iWidth = i.getWidth(null);
        int iHeight = i.getHeight(null);
        //int w, h;

        if (iWidth > iHeight) {
            tumb1 = i.getScaledInstance(t1, (t1 * iHeight) / iWidth, Image.SCALE_SMOOTH);
            tumb2 = i.getScaledInstance(t2, (t2 * iHeight) / iWidth, Image.SCALE_SMOOTH);
            tumb3 = i.getScaledInstance(t3, (t3 * iHeight) / iWidth, Image.SCALE_SMOOTH);
            tumb4 = i.getScaledInstance(t4, (t4 * iHeight) / iWidth, Image.SCALE_SMOOTH);
            //w = t4;
            //h = (t4 * iHeight) / iWidth;
        } else {
            tumb1 = i.getScaledInstance((t1 * iWidth) / iHeight, t1, Image.SCALE_SMOOTH);
            tumb2 = i.getScaledInstance((t2 * iWidth) / iHeight, t2, Image.SCALE_SMOOTH);
            tumb3 = i.getScaledInstance((t3 * iWidth) / iHeight, t3, Image.SCALE_SMOOTH);
            tumb4 = i.getScaledInstance((t4 * iWidth) / iHeight, t4, Image.SCALE_SMOOTH);
            //w = (t4 * iWidth) / iHeight;
            //h = t4;
        }

        tumb4 = estampar(tumb4);

        Util.log("Salvando Imagens");

        save(tumb1, diretorio + File.separator + "_a" + arquivo);
        save(tumb2, diretorio + File.separator + "_b" + arquivo);
        save(tumb3, diretorio + File.separator + "_c" + arquivo);
        save(tumb4, diretorio + File.separator + "_d" + arquivo);

    } catch (Exception e) {
        Util.err.println("[Thumbnail.makeThumbs]/ERRO: Inesperado - " + e.getMessage());
        e.printStackTrace(Util.err);
    }
}

From source file:ca.sfu.federation.utils.ParametricModelFilter.java

/**
 * Determine whether the file is a directory.
 * @param f File./*from  w w w .  j a  va 2s .c  om*/
 * @return True if the file is a directory, false otherwise.
 */
public boolean accept(File f) {
    try {
        if (f.getCanonicalPath().endsWith("\\.mdl")) {
            return true;
        }
    } catch (IOException ex) {
        String stack = ExceptionUtils.getFullStackTrace(ex);
        logger.log(Level.WARNING, "{0}", stack);
    }
    return false;
}

From source file:m3umaker.exFiles.java

public List getFiles(String Mdir, String[] extensions) {
    List<File> files = null;
    try {// ww w  .j  a v a 2  s  .  co m
        File dir = new File(Mdir);
        mDIR = dir.getCanonicalPath();
        files = (List<File>) FileUtils.listFiles(dir, extensions, true);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return files;
}

From source file:cinematicketsim.DateTimeClassParser.java

public ArrayList<DateTime> loadData(String filename) {

    ArrayList<DateTime> dateTimeData = new ArrayList<DateTime>();

    try {//from  w ww . j a  va  2 s . c o m
        File f = new File(filename);
        filename = f.getCanonicalPath();

    } catch (Exception e) {
        e.printStackTrace();
    }

    FileResource file = new FileResource(filename);

    CSVParser parser = file.getCSVParser();

    for (CSVRecord record : parser) {

        String movieId = record.get("id");

        String showDate = record.get("date");

        String showTime = record.get("time");

        DateTime movieInfo = new DateTime(movieId, showDate, showTime);

        dateTimeData.add(movieInfo);

    }

    return dateTimeData;
}

From source file:m3umaker.exFiles.java

public List getFiles(String Mdir) {
    List<File> files0 = null;
    try {/*w  ww.j av a  2  s  . c  o  m*/
        File dir = new File(Mdir);
        mDIR = dir.getCanonicalPath();
        String[] extensions = new String[] { "mp3", "wma", "flac", "aac", "amr", "m4a", "m4r", "ogg", "wav",
                "wavepack", "wma", "flac", "aac", "amr", "m4a", "m4r", "ogg", "wav", "wavepack", "avi", "flv",
                "mp4", "wmv", "3gp", "rmvb", "mkv", "mpg", "vob", "mov" };
        files0 = (List<File>) FileUtils.listFiles(dir, extensions, true);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return files0;
}

From source file:com.el.ecom.utils.ImageUtils.java

/**
 * ?/*  w  w  w  . j  a  v a  2 s.  c  om*/
 * 
 * @param srcFile ?
 * @param destFile 
 * @param watermarkFile ?
 * @param watermarkPosition ??
 * @param alpha ??
 */
public static void addWatermark(File srcFile, File destFile, File watermarkFile,
        WatermarkPosition watermarkPosition, int alpha) {
    Assert.notNull(srcFile);
    Assert.state(srcFile.exists());
    Assert.state(srcFile.isFile());
    Assert.notNull(destFile);
    Assert.state(alpha >= 0);
    Assert.state(alpha <= 100);

    if (watermarkFile == null || !watermarkFile.exists() || !watermarkFile.isFile() || watermarkPosition == null
            || watermarkPosition == WatermarkPosition.no) {
        try {
            if (!StringUtils.equals(srcFile.getCanonicalPath(), destFile.getCanonicalPath())) {
                FileUtils.copyFile(srcFile, destFile);
            }
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        return;
    }
    if (type == Type.jdk) {
        Graphics2D graphics2D = null;
        ImageOutputStream imageOutputStream = null;
        ImageWriter imageWriter = null;
        try {
            BufferedImage srcBufferedImage = ImageIO.read(srcFile);
            int srcWidth = srcBufferedImage.getWidth();
            int srcHeight = srcBufferedImage.getHeight();
            BufferedImage destBufferedImage = new BufferedImage(srcWidth, srcHeight,
                    BufferedImage.TYPE_INT_RGB);
            graphics2D = destBufferedImage.createGraphics();
            graphics2D.setBackground(BACKGROUND_COLOR);
            graphics2D.clearRect(0, 0, srcWidth, srcHeight);
            graphics2D.drawImage(srcBufferedImage, 0, 0, null);
            graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha / 100F));

            BufferedImage watermarkBufferedImage = ImageIO.read(watermarkFile);
            int watermarkImageWidth = watermarkBufferedImage.getWidth();
            int watermarkImageHeight = watermarkBufferedImage.getHeight();
            int x = srcWidth - watermarkImageWidth;
            int y = srcHeight - watermarkImageHeight;
            if (watermarkPosition == WatermarkPosition.topLeft) {
                x = 0;
                y = 0;
            } else if (watermarkPosition == WatermarkPosition.topRight) {
                x = srcWidth - watermarkImageWidth;
                y = 0;
            } else if (watermarkPosition == WatermarkPosition.center) {
                x = (srcWidth - watermarkImageWidth) / 2;
                y = (srcHeight - watermarkImageHeight) / 2;
            } else if (watermarkPosition == WatermarkPosition.bottomLeft) {
                x = 0;
                y = srcHeight - watermarkImageHeight;
            } else if (watermarkPosition == WatermarkPosition.bottomRight) {
                x = srcWidth - watermarkImageWidth;
                y = srcHeight - watermarkImageHeight;
            }
            graphics2D.drawImage(watermarkBufferedImage, x, y, watermarkImageWidth, watermarkImageHeight, null);

            imageOutputStream = ImageIO.createImageOutputStream(destFile);
            imageWriter = ImageIO.getImageWritersByFormatName(FilenameUtils.getExtension(destFile.getName()))
                    .next();
            imageWriter.setOutput(imageOutputStream);
            ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
            imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            imageWriteParam.setCompressionQuality(DEST_QUALITY / 100F);
            imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam);
            imageOutputStream.flush();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            if (graphics2D != null) {
                graphics2D.dispose();
            }
            if (imageWriter != null) {
                imageWriter.dispose();
            }
            try {
                if (imageOutputStream != null) {
                    imageOutputStream.close();
                }
            } catch (IOException e) {
            }
        }
    } else {
        String gravity = "SouthEast";
        if (watermarkPosition == WatermarkPosition.topLeft) {
            gravity = "NorthWest";
        } else if (watermarkPosition == WatermarkPosition.topRight) {
            gravity = "NorthEast";
        } else if (watermarkPosition == WatermarkPosition.center) {
            gravity = "Center";
        } else if (watermarkPosition == WatermarkPosition.bottomLeft) {
            gravity = "SouthWest";
        } else if (watermarkPosition == WatermarkPosition.bottomRight) {
            gravity = "SouthEast";
        }
        IMOperation operation = new IMOperation();
        operation.gravity(gravity);
        operation.dissolve(alpha);
        operation.quality((double) DEST_QUALITY);
        try {
            operation.addImage(watermarkFile.getCanonicalPath());
            operation.addImage(srcFile.getCanonicalPath());
            operation.addImage(destFile.getCanonicalPath());
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        if (type == Type.graphicsMagick) {
            CompositeCmd compositeCmd = new CompositeCmd(true);
            if (graphicsMagickPath != null) {
                compositeCmd.setSearchPath(graphicsMagickPath);
            }
            try {
                compositeCmd.run(operation);
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (InterruptedException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (IM4JavaException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        } else {
            CompositeCmd compositeCmd = new CompositeCmd(false);
            if (imageMagickPath != null) {
                compositeCmd.setSearchPath(imageMagickPath);
            }
            try {
                compositeCmd.run(operation);
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (InterruptedException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (IM4JavaException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    }
}