Example usage for java.io File renameTo

List of usage examples for java.io File renameTo

Introduction

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

Prototype

public boolean renameTo(File dest) 

Source Link

Document

Renames the file denoted by this abstract pathname.

Usage

From source file:fr.gael.dhus.server.http.webapp.solr.SolrWebapp.java

@Override
public void afterPropertiesSet() throws Exception {
    try {/*from w w  w.j  av a  2s.  c om*/
        SolrConfiguration solr = configurationManager.getSolrConfiguration();

        File solrroot = new File(solr.getPath());
        System.setProperty("solr.solr.home", solrroot.getAbsolutePath());

        if (Boolean.getBoolean("dhus.solr.reindex")) {
            // reindexing
            try {
                LOGGER.info("Reindex: deleting " + solrroot);
                FileUtils.deleteDirectory(solrroot);
            } catch (IllegalArgumentException | IOException ex) {
                LOGGER.error("Cannot delete solr root directory " + ex.getMessage());
            }
        }

        File libdir = new File(solrroot, "lib");
        libdir.mkdirs();
        File coredir = new File(solrroot, "dhus");
        coredir.mkdirs();
        File confdir = new File(coredir, "conf");

        // Move old data/conf dirs if any
        File olddata = new File(solrroot, "data/dhus");
        if (olddata.exists()) {
            File newdata = new File(coredir, "data");
            olddata.renameTo(newdata);
        }
        File oldconf = new File(solrroot, "conf");
        if (oldconf.exists()) {
            oldconf.renameTo(confdir);
        }
        confdir.mkdirs();

        // Rename old `schema.xml` file to `managed-schema`
        File schemafile = new File(confdir, "managed-schema");
        File oldschema = new File(confdir, "schema.xml");
        if (oldschema.exists()) {
            oldschema.renameTo(schemafile);
        }

        // solr.xml
        InputStream input = ClassLoader
                .getSystemResourceAsStream("fr/gael/dhus/server/http/webapp/solr/cfg/solr.xml");
        OutputStream output = new FileOutputStream(new File(solrroot, "solr.xml"));
        IOUtils.copy(input, output);
        output.close();
        input.close();

        // dhus/core.properties
        input = ClassLoader
                .getSystemResourceAsStream("fr/gael/dhus/server/http/webapp/solr/cfg/core.properties");
        File core_props = new File(coredir, "core.properties");
        output = new FileOutputStream(core_props);
        IOUtils.copy(input, output);
        output.close();
        input.close();

        // dhus/solrconfig.xml
        input = ClassLoader
                .getSystemResourceAsStream("fr/gael/dhus/server/http/webapp/solr/cfg/solrconfig.xml");
        File solrconfigfile = new File(confdir, "solrconfig.xml");
        output = new FileOutputStream(solrconfigfile);
        IOUtils.copy(input, output);
        output.close();
        input.close();

        // dhus/schema.xml
        if (!schemafile.exists()) {
            String schemapath = solr.getSchemaPath();
            if ((schemapath == null) || ("".equals(schemapath)) || (!(new File(schemapath)).exists())) {
                input = ClassLoader
                        .getSystemResourceAsStream("fr/gael/dhus/server/http/webapp/solr/cfg/schema.xml");
            } else {
                input = new FileInputStream(new File(schemapath));
            }
            output = new FileOutputStream(schemafile);
            IOUtils.copy(input, output);
            output.close();
            input.close();
        }

        // dhus/stopwords.txt
        input = ClassLoader.getSystemResourceAsStream("fr/gael/dhus/server/http/webapp/solr/cfg/stopwords.txt");
        output = new FileOutputStream(new File(confdir, "stopwords.txt"));
        IOUtils.copy(input, output);
        output.close();
        input.close();

        // dhus/synonyms.txt
        String synonympath = solr.getSynonymPath();
        if ((synonympath == null) || ("".equals(synonympath)) || (!(new File(synonympath)).exists())) {
            input = ClassLoader
                    .getSystemResourceAsStream("fr/gael/dhus/server/http/webapp/solr/cfg/synonyms.txt");
        } else {
            input = new FileInputStream(new File(synonympath));
        }
        output = new FileOutputStream(new File(confdir, "synonyms.txt"));
        IOUtils.copy(input, output);
        output.close();
        input.close();

        // dhus/xslt/opensearch_atom.xsl
        input = ClassLoader
                .getSystemResourceAsStream("fr/gael/dhus/server/http/webapp/solr/cfg/xslt/opensearch_atom.xsl");
        if (input != null) {
            File xslt_dir = new File(confdir, "xslt");
            if (!xslt_dir.exists()) {
                xslt_dir.mkdirs();
            }
            output = new FileOutputStream(new File(xslt_dir, "opensearch_atom.xsl"));
            IOUtils.copy(input, output);
            output.close();
            input.close();
        } else {
            LOGGER.warn("Cannot file opensearch xslt file. " + "Opensearch interface is not available.");
        }

        // dhus/conf/suggest.dic
        try (InputStream in = ClassLoader.getSystemResourceAsStream("suggest.dic")) {
            File suggest_dict = new File(confdir, "suggest.dic");
            if (in != null) {
                LOGGER.info("Solr config file `suggest.dic` found");
                try (OutputStream out = new FileOutputStream(suggest_dict)) {
                    IOUtils.copy(in, out);
                }
            } else {
                LOGGER.warn("Solr config file `suggest.dic` not found");
                suggest_dict.createNewFile();
            }
        }

        solrInitializer.createSchema(coredir.toPath(), schemafile.getAbsolutePath());

    } catch (IOException e) {
        throw new UnsupportedOperationException("Cannot initialize Solr service.", e);
    }
}

From source file:com.ephesoft.dcma.util.FileUtils.java

/**
 * To move Directory and Contents./*from  ww w.ja  va2 s  .  c o m*/
 * @param sourceDirPath {@link String}
 * @param destDirPath {@link String}
 * @return boolean
 */
public static boolean moveDirectoryAndContents(String sourceDirPath, String destDirPath) {
    boolean success = true;
    File sourceDir = new File(sourceDirPath);
    File destDir = new File(destDirPath);
    if (sourceDir.exists() && destDir.exists()) {
        // delete the directory if it already exists
        deleteDirectoryAndContentsRecursive(destDir);
        success = sourceDir.renameTo(destDir);
    }
    return success;
}

From source file:com.sfs.jbtimporter.JBTImporter.java

/**
 * Transform the issues to the new XML format.
 *
 * @param jbt the jbt processor/*  www .j  ava  2  s  .  co  m*/
 * @param issues the issues
 */
private static void transformIssues(final JBTProcessor jbt, final List<JBTIssue> issues) {

    final File xsltFile = new File(jbt.getXsltFileName());

    final Source xsltSource = new StreamSource(xsltFile);
    final TransformerFactory transFact = TransformerFactory.newInstance();
    Transformer trans = null;

    try {
        final Templates cachedXSLT = transFact.newTemplates(xsltSource);
        trans = cachedXSLT.newTransformer();
    } catch (TransformerConfigurationException tce) {
        System.out.println("ERROR configuring XSLT engine: " + tce.getMessage());
    }
    // Enable indenting and UTF8 encoding
    trans.setOutputProperty(OutputKeys.INDENT, "yes");
    trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

    if (trans != null) {
        for (JBTIssue issue : issues) {
            System.out.println("Processing Issue ID: " + issue.getId());
            System.out.println("Filename: " + issue.getFullFileName());

            // Read the XML file
            final File xmlFile = new File(issue.getFullFileName());
            final File tempFile = new File(issue.getFullFileName() + ".tmp");
            final File originalFile = new File(issue.getFullFileName() + ".old");

            Source xmlSource = null;
            if (originalFile.exists()) {
                // The original file exists, use that as the XML source
                xmlSource = new StreamSource(originalFile);
            } else {
                // No backup exists, use the .xml file.
                xmlSource = new StreamSource(xmlFile);
            }

            // Transform the XML file
            try {
                trans.transform(xmlSource, new StreamResult(tempFile));

                if (originalFile.exists()) {
                    // Delete the .xml file as it needs to be replaced
                    xmlFile.delete();
                } else {
                    // Rename the existing file with the .old extension
                    xmlFile.renameTo(originalFile);
                }
            } catch (TransformerException te) {
                System.out.println("ERROR transforming XML: " + te.getMessage());
            }

            // Read the xmlFile and convert the special characters

            OutputStreamWriter out = null;
            try {

                final BufferedReader in = new BufferedReader(
                        new InputStreamReader(new FileInputStream(tempFile), "UTF8"));

                out = new OutputStreamWriter(new FileOutputStream(xmlFile), "UTF-8");

                int ch = -1;
                ch = in.read();
                while (ch != -1) {
                    final char c = (char) ch;

                    if (jbt.getSpecialCharacterMap().containsKey(c)) {
                        // System.out.println("Replacing character: " + c 
                        //        + ", " + jbt.getSpecialCharacterMap().get(c));
                        out.write(jbt.getSpecialCharacterMap().get(c));
                    } else {
                        out.write(c);
                    }
                    ch = in.read();
                }
            } catch (IOException ie) {
                System.out.println("ERROR converting special characters: " + ie.getMessage());
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                } catch (IOException ie) {
                    System.out.println("ERROR closing the XML file: " + ie.getMessage());
                }
                // Delete the temporary file
                tempFile.delete();
            }

            System.out.println("-------------------------------------");
        }
    }
}

From source file:de.uni_siegen.wineme.come_in.thumbnailer.util.TemporaryFilesManager.java

/**
 * Create a new, read-only temporary file.
 * //from www.ja  v a 2  s .  com
 * @param file         Original file that you need a copy of
 * @param newExtension   The extension that the new file should have
 * @return File (read-only) 
 * @throws IOException
 */
public File createTempfileCopy(File file, String newExtension) throws IOException {
    File destFile = files.get(file);
    if (destFile == null) {
        destFile = File.createTempFile("temp", "." + newExtension);
        createNewCopy(file, destFile);
        destFile.setWritable(false, false);
    } else {
        String newFilename = FilenameUtils.removeExtension(destFile.getAbsolutePath()) + "." + newExtension;
        File newFile = new File(newFilename);
        boolean renameSucces = destFile.renameTo(newFile);
        if (!renameSucces) {
            createNewCopy(file, newFile);
        }
        files.put(file, newFile);
        destFile = newFile;
    }
    return destFile;
}

From source file:io.treefarm.plugins.haxe.components.nativeProgram.AbstractNativeProgram.java

private File getDirectory(Artifact artifact) throws Exception {
    File destinationDirectory = getDestinationDirectoryForArtifact(artifact);

    if (!destinationDirectory.exists()
            || artifact.getFile().lastModified() > destinationDirectory.lastModified()) {
        if (destinationDirectory.exists()) {
            FileUtils.deleteQuietly(destinationDirectory);
        }//from   w  w w.  j  a v a2 s  .co m
        File unpackDir = new File(outputDirectory, getUniqueArtifactPath() + "-unpack");

        if (unpackDir.exists())
            FileUtils.deleteQuietly(unpackDir);

        UnpackHelper unpackHelper = new UnpackHelper() {
        };
        DefaultUnpackMethods unpackMethods = new DefaultUnpackMethods(logger);
        unpackHelper.unpack(unpackDir, artifact, unpackMethods, null);

        for (String fileName : unpackDir.list()) {
            if (artifact.getType().equals("jar")) {
                fileName = getUniqueArtifactPath();
            }
            File firstFile = new File(unpackDir, fileName);
            //FileUtils.moveDirectory(firstFile, destinationDirectory);
            firstFile.renameTo(destinationDirectory);
            if (!destinationDirectory.exists()) {
                // manually move using shell call as last ditch
                Process process = Runtime.getRuntime().exec(
                        "mv " + firstFile.getAbsolutePath() + " " + destinationDirectory.getAbsolutePath());
            }
            break;
        }

        if (destinationDirectory.exists()) {
            destinationDirectory.setLastModified(artifact.getFile().lastModified());
        }
        if (unpackDir.exists())
            FileUtils.deleteQuietly(unpackDir);
    }

    initialized = true;
    String directoryPath = destinationDirectory.getAbsolutePath();
    // Add current directory to path
    path.add(directoryPath);
    return destinationDirectory;
}

From source file:File.WriteNewTrack.java

/**
 * Metda processRequest je obslun metda, ktor sa vol po vyvolan danho servletu na strane pouvatea. 
 * Pri?om sa servlet vykonva na strane servera.
 * @param request - objekt poiadavky, ktor sa prena zo strany klienta na stranu servera
 * @param response - objekt odozvy servera, ktor sa prena zo strany servera na stranu klienta
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 *//*from  ww  w .  j ava 2 s  .  co m*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession();
    String trackName = session.getAttribute("trackName").toString();
    String trackDescr = session.getAttribute("trackDescr").toString();
    String trackActivity = session.getAttribute("trackActivity").toString();
    String access = session.getAttribute("access").toString();

    session.setAttribute("trackNameExist", "False");
    //        if (system.startsWith("Windows")) {
    //            String tempPath = "D:\\GitHub\\GPSWebApp\\web\\Logged\\uploaded_from_server\\" + session.getAttribute("username") + "\\Temp" + "\\";
    //            //String tempPath = "E:\\SCHOOL\\TUKE\\DIPLOMOVKA\\PRAKTICKA CAST\\GITHUB\\GPSWebApp\\web\\Logged\\uploaded_from_server\\" + session.getAttribute("username") + "\\Temp" + "\\";
    //            File tempFile = new File(tempPath);
    //            if (tempFile.exists()) {
    //                System.out.println("Mam temp a vymazujem!");
    //                FileUtils.deleteDirectory(tempFile);
    //                //tempFile.delete();
    //                FileLogger.getInstance().createNewLog("Warning: Found old temp folder which belongs to " + session.getAttribute("username") + " !!! Successfuly delete the old temp.");
    //            }
    //        } else {
    //            String tempPath = "/usr/local/tomcat/webapps/ROOT/Logged/uploaded_from_server/" + session.getAttribute("username") + "/Temp" + "/";
    //            File tempFile = new File(tempPath);
    //            if (tempFile.exists()) {
    //                System.out.println("Mam temp a vymazujem!");
    //                FileUtils.deleteDirectory(tempFile);
    //                FileLogger.getInstance().createNewLog("Warning: Found old temp folder which belongs to " + session.getAttribute("username") + " !!! Successfuly delete the old temp.");
    //            }
    //        }

    if (system.startsWith("Windows")) {
        //pathToFile = "D:\\GitHub\\GPSWebApp\\web\\Logged\\uploaded_from_server\\" + session.getAttribute("username") + "\\Temp" + "\\";
        //pathToMultimedia = "D:\\GitHub\\GPSWebApp\\web\\Logged\\uploaded_from_server\\" + session.getAttribute("username") + "\\Temp" + "\\Multimedia\\";
        pathToFile = "E:\\SCHOOL\\TUKE\\DIPLOMOVKA\\PRAKTICKA CAST\\GITHUB\\GPSWebApp\\web\\Logged\\uploaded_from_server\\"
                + session.getAttribute("username") + "\\Temp" + "\\";
        pathToMultimedia = "E:\\SCHOOL\\TUKE\\DIPLOMOVKA\\PRAKTICKA CAST\\GITHUB\\GPSWebApp\\web\\Logged\\uploaded_from_server\\"
                + session.getAttribute("username") + "\\Temp" + "\\Multimedia\\";
    } else {
        pathToFile = "/usr/local/tomcat/webapps/ROOT/Logged/uploaded_from_server/"
                + session.getAttribute("username") + "/Temp" + "/";
        pathToMultimedia = "/usr/local/tomcat/webapps/ROOT/Logged/uploaded_from_server/"
                + session.getAttribute("username") + "/Temp" + "/Multimedia/";
    }

    File tempF = new File(pathToFile + "Temp.txt");
    if (tempF.exists()) {
        FileUtils.forceDelete(tempF);
        FileLogger.getInstance()
                .createNewLog("Warning: Found tamp file Temp.txt in WriteNewTrack which belongs to user "
                        + session.getAttribute("username") + " while writing new track " + trackName + " !!!");
    }

    File multF = new File(pathToMultimedia);
    MultimediaSearcher searcher = new MultimediaSearcher();
    searcher.setSearchFolder(pathToMultimedia);
    String[] files = searcher.startSearchWithoutTrack();
    if (files.length >= 1) {
        session.setAttribute("isMultimedia", "True");
    }

    new File(pathToFile).mkdirs();
    File file = new File(pathToFile, "Temp.txt"); // Write to destination file. Pouyivaj filename!
    boolean create = file.createNewFile();
    //System.out.println("Vytvoril: " + create);

    if (file.exists()) {
        String latLngStr = request.getParameter("textBox");

        FileWriter writer = new FileWriter(file, true);
        BufferedWriter buf = new BufferedWriter(writer);

        writer.append(latLngStr);

        buf.close();
        writer.close();
    }
    if (session.getAttribute("isMultimedia") != null) {
        request.getRequestDispatcher("SynchronizeDrawTrack.jsp").forward(request, response);
    } else {
        try {

            String pathToTemp;
            String pathToTempFile;
            String pathToMultimediaFiles;

            String filename = trackName + ".gpx";
            if (system.startsWith("Windows")) {
                //pathToFile = "D:\\GitHub\\GPSWebApp\\web\\Logged\\uploaded_from_server\\" + session.getAttribute("username") + "\\" + trackName + "\\";
                //pathToTemp = "D:\\GitHub\\GPSWebApp\\web\\Logged\\uploaded_from_server\\" + session.getAttribute("username") + "\\" + "Temp" + "\\";
                //pathToTempFile = pathToFile + "Temp.txt";
                pathToFile = "E:\\SCHOOL\\TUKE\\DIPLOMOVKA\\PRAKTICKA CAST\\GITHUB\\GPSWebApp\\web\\Logged\\uploaded_from_server\\"
                        + session.getAttribute("username") + "\\" + trackName + "\\";
                pathToTemp = "E:\\SCHOOL\\TUKE\\DIPLOMOVKA\\PRAKTICKA CAST\\GITHUB\\GPSWebApp\\web\\Logged\\uploaded_from_server\\"
                        + session.getAttribute("username") + "\\" + "Temp" + "\\";
                pathToTempFile = pathToFile + "Temp.txt";
                pathToMultimediaFiles = pathToFile + "Multimedia" + "\\";
                //                    File fTemp = new File(pathToMultimediaFiles);
                //                    if(!fTemp.exists()){
                //                        fTemp.mkdirs();
                //                    }
            } else {
                pathToFile = "/usr/local/tomcat/webapps/ROOT/Logged/uploaded_from_server/"
                        + session.getAttribute("username") + "/" + trackName + "/";
                pathToTemp = "/usr/local/tomcat/webapps/ROOT/Logged/uploaded_from_server/"
                        + session.getAttribute("username") + "/" + "Temp" + "/";
                pathToTempFile = pathToFile + "Temp.txt";
                pathToMultimediaFiles = pathToFile + "Multimedia" + "/";
                //                    File fTemp = new File(pathToMultimediaFiles);
                //                    if(!fTemp.exists()){
                //                        fTemp.mkdirs();
                //                    }
            }

            File oldFile = new File(pathToTemp);
            File newFile = new File(pathToFile);
            oldFile.renameTo(newFile);

            GPXParser parser = new GPXParser(pathToFile, filename, session.getAttribute("username").toString(),
                    trackName);
            parser.readFromTrackPoints(pathToTempFile, trackName, trackDescr);
            FileLogger.getInstance().createNewLog("For user " + session.getAttribute("username")
                    + "was successfuly created GPXParser in STEP 3 for track " + trackName + " .");
            parser.searchForMultimediaFilesWithoutCorrection(pathToMultimediaFiles);

            FileLogger.getInstance().createNewLog("For user " + session.getAttribute("username")
                    + "was successfuly founded multimedia files in STEP 3 for track " + trackName + " .");
            parser.parseFromTrackPoints(trackActivity, trackDescr);
            FileLogger.getInstance().createNewLog("For user " + session.getAttribute("username")
                    + "was successfuly parsed GPX file in STEP 3 for track " + trackName + " .");
            parser.createGPXFile(trackDescr);
            FileLogger.getInstance().createNewLog("For user " + session.getAttribute("username")
                    + "was successfuly generated GPX file in STEP 3 for track " + trackName + " .");

            DBTrackCreator tCreator = new DBTrackCreator();
            DBLoginFinder finder = new DBLoginFinder();

            tCreator.createNewTrack(trackName, trackDescr, trackActivity, pathToFile,
                    finder.getUserId(session.getAttribute("username").toString()),
                    parser.getStartAndEndDate().get(0).toString(),
                    parser.getStartAndEndDate().get(1).toString(), access, parser.getStartAddress(),
                    parser.getEndAddress(), parser.getTrackLengthKm(), parser.getTrackMinElevation(),
                    parser.getTrackMaxElevation(), parser.getTrackHeightDiff(), parser.getTrackDuration(),
                    "Drawed");

            TLVLoader loader = new TLVLoader();
            loader.readTLVFile(pathToFile, trackName);
            PDFTrackGenerator generator = new PDFTrackGenerator(loader, pathToFile, trackName);
            generator.generateTrackPDFA4(2, null, 640, 640, 1, parser.getStartAndEndDate().get(0).toString(),
                    parser.getStartAndEndDate().get(1).toString(), trackActivity,
                    session.getAttribute("username").toString());

            FileLogger.getInstance().createNewLog("For user " + session.getAttribute("username")
                    + "was successfuly created new track in STEP 3 for track " + trackName + " .");

            if (loader.getTrackPoints().get(0).getInternetElevation() == 0 && loader.getTrackPoints()
                    .get(loader.getTrackPoints().size() - 1).getInternetElevation() == 0) {
                session.setAttribute("Limit", "True");
            }

        } catch (Exception ex) {
            System.out.println("Error: Unable to create .tlv file!");
            FileLogger.getInstance().createNewLog("ERROR: Unable to create user's "
                    + request.getSession().getAttribute("username") + " track " + trackName + " in STEP 3 !!!");
            //vloyit oznacenie chyby parsera!!!
            ex.printStackTrace();
        }
        request.getRequestDispatcher("ShowTracks.jsp").forward(request, response);
    }

}

From source file:com.openedit.util.FileUtils.java

protected void renameFile(File inSource, File inDest, boolean inForce) throws IOException {
    if (!inSource.renameTo(inDest)) {
        if (inForce) {
            copyFiles(inSource, inDest);
            boolean deleted = inSource.delete();
            if (!deleted) {
                log.info("could not delete file - " + inSource);
            }//from  ww  w .  j  ava 2 s  .  com
            return;
        }
        throw new IOException("Could not move " + inSource.getPath() + " to " + inDest.getPath()
                + " file may already exist. Use forced=true");
    }

}

From source file:hoot.services.controllers.ingest.BasemapResource.java

protected void _toggleBaseMap(String bmName, boolean enable) throws Exception {
    String fileName = _ingestStagingPath + "/BASEMAP/" + bmName;
    String targetName = _ingestStagingPath + "/BASEMAP/" + bmName;
    ;//from   w w  w .  j  a  va 2 s  .c  om
    if (enable) {
        fileName += ".disabled";
        targetName += ".enabled";
    } else {
        fileName += ".enabled";
        targetName += ".disabled";
    }
    File sourceFile = new File(fileName);
    File destFile = new File(targetName);
    if (sourceFile.exists()) {
        boolean res = sourceFile.renameTo(destFile);
        if (res == false) {
            throw new Exception("Failed to rename file:" + fileName + " to " + targetName);
        }
    } else {
        throw new Exception("Can not enable file:" + fileName + ". It does not exist.");
    }
}

From source file:com.nit.vicky.servicelayer.NoteService.java

/**
 * Considering the field is new, if it has media handle it
 * /*w  ww  .  j  a  v  a  2 s .com*/
 * @param field
 */
private static void importMediaToDirectory(IField field, Context context) {
    String tmpMediaPath = null;
    switch (field.getType()) {
    case AUDIO:
        tmpMediaPath = field.getAudioPath();
        break;

    case IMAGE:
        tmpMediaPath = field.getImagePath();
        break;

    case TEXT:
    default:
        break;
    }
    if (tmpMediaPath != null) {
        try {
            File inFile = new File(tmpMediaPath);
            if (inFile.exists()) {
                Collection col = AnkiDroidApp.getCol();
                String mediaDir = col.getMedia().getDir() + "/";

                File mediaDirFile = new File(mediaDir);

                File parent = inFile.getParentFile();

                // If already there.
                if (mediaDirFile.getAbsolutePath().contentEquals(parent.getAbsolutePath())) {
                    return;
                }

                //File outFile = new File(mediaDir + inFile.getName().replaceAll(" ", "_"));

                //if (outFile.exists()) {

                File outFile = null;

                if (field.getType() == EFieldType.IMAGE) {
                    outFile = File.createTempFile("imggallery", ".jpg", DiskUtil.getStoringDirectory());
                } else if (field.getType() == EFieldType.AUDIO) {
                    outFile = File.createTempFile("soundgallery", ".mp3", DiskUtil.getStoringDirectory());
                }

                //}

                if (field.hasTemporaryMedia()) {
                    // Move
                    inFile.renameTo(outFile);
                } else {
                    // Copy
                    InputStream in = new FileInputStream(tmpMediaPath);
                    OutputStream out = new FileOutputStream(outFile.getAbsolutePath());

                    byte[] buf = new byte[1024];
                    int len;
                    while ((len = in.read(buf)) > 0) {
                        out.write(buf, 0, len);
                    }
                    in.close();
                    out.close();
                }

                switch (field.getType()) {
                case AUDIO:
                    field.setAudioPath(outFile.getAbsolutePath());
                    break;

                case IMAGE:
                    field.setImagePath(outFile.getAbsolutePath());
                    break;
                default:
                    break;
                }

                Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                scanIntent.setData(Uri.fromFile(inFile));
                context.sendBroadcast(scanIntent);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:models.Attachment.java

/**
 * Moves a file to the Upload Directory.
 *
 * This method is used to move a file stored in temporary directory by
 * PlayFramework to the Upload Directory managed by Yobi.
 *
 * @param file/* ww  w  .j  a v  a2s . co  m*/
 * @return SHA1 hash of the file
 * @throws NoSuchAlgorithmException
 * @throws IOException
 */
private static String moveFileIntoUploadDirectory(File file) throws NoSuchAlgorithmException, IOException {
    // Compute sha1 checksum.
    MessageDigest algorithm = MessageDigest.getInstance("SHA1");
    byte buf[] = new byte[10240];
    FileInputStream fis = new FileInputStream(file);
    for (int size = 0; size >= 0; size = fis.read(buf)) {
        algorithm.update(buf, 0, size);
    }
    Formatter formatter = new Formatter();
    for (byte b : algorithm.digest()) {
        formatter.format("%02x", b);
    }
    String hash = formatter.toString();
    formatter.close();
    fis.close();

    // Store the file.
    // Before do that, create upload directory if it doesn't exist.
    File uploads = new File(uploadDirectory);
    uploads.mkdirs();
    if (!uploads.isDirectory()) {
        throw new NotDirectoryException("'" + file.getAbsolutePath() + "' is not a directory.");
    }
    File attachedFile = new File(uploadDirectory, hash);
    boolean isMoved = file.renameTo(attachedFile);

    if (!isMoved) {
        FileUtils.copyFile(file, attachedFile);
        file.delete();
    }

    // Close all resources.

    return hash;
}