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:br.com.renatoccosta.regexrenamer.Renamer.java

/**
 * Executes the actual renaming process if everything is ready. Before
 * calling this method, the {@code previewRename()} must be called.
 *//*  w  w  w .ja v  a  2s.c  o  m*/
public void rename() throws RenamerException {
    if (!isReady() || this.dirty || !this.canRename) {
        throw new RenamerException(Messages.getNotReadyMessage());
    }

    if (hasConflicts()) {
        throw new RenamerException(Messages.getConflictMessage());
    }

    /*
     * o ato de renomear  feito em dois passos para que no existam
     * conflitos de nomes de arquivos entre os nomes de origem e os de
     * destino.
     *
     * ex:
     * joao -> maria
     * maria -> joao
     *
     * se 'joao' fosse renomeado diretamente para 'maria', existiria um
     * conflito de nomes (existe um arquivo com o nome 'maria').
     *
     * joao -> joao~
     * maria -> maria~
     * joao~ -> maria
     * maria~ -> joao
     *
     * desta forma no existe conflito de nome.
     */

    //renomea para o temporrio
    //apenas os arquivos que tiverem alteraes nos nomes
    for (RenamedFile f : files) {
        if (f.shouldRename()) {
            File file = new File(f.getFileNameBefore());
            file.renameTo(new File(f.getFileNameBefore() + TMP_SUFIX));
        }
    }

    //renomea para o definitivo
    //apenas os arquivos que tiverem alteraes nos nomes
    for (RenamedFile f : files) {
        if (f.shouldRename()) {
            File file = new File(f.getFileNameBefore() + TMP_SUFIX);
            file.renameTo(new File(f.getFileNameAfter()));
        }
    }

    fillFileLists();

    this.dirty = true;
}

From source file:com.imos.sample.pi.ControlGpioExample.java

public void pythonTemperatureSensor() {

    try {//from   w w w.j  ava  2s.  co m
        String cmd = "sudo python /home/pi/Adafruit_Python_DHT/examples/AdafruitDHT.py 11 4";
        int count = 0;
        JSONArray array = new JSONArray();
        int dayOfMonth = 0;
        cal.setTime(new Date());
        dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
        while (true) {
            Process p = Runtime.getRuntime().exec(cmd);
            p.waitFor();

            StringBuilder output = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                output.append(line);
            }
            String result = output.toString(), tempStr;
            double temp, humid;
            if (!result.trim().isEmpty()) {
                tempStr = result.substring(result.indexOf("Humid"));
                result = result.substring(result.indexOf("=") + 1, result.indexOf("C") - 1);
                temp = Double.parseDouble(result);
                result = tempStr;
                result = result.substring(result.indexOf("=") + 1, result.indexOf("%"));
                humid = Double.parseDouble(result);

                JSONObject data = new JSONObject();
                data.put("temp", temp);
                data.put("humid", humid);
                data.put("time", new Date().getTime());

                array.put(data);
            }

            Thread.sleep(60000);
            count++;
            if (count == 60) {
                Logger.getLogger(PiMainFile.class.getName()).log(Level.INFO, null, "");
                cal.setTime(new Date());
                StringBuilder builder = new StringBuilder();
                builder.append(cal.get(Calendar.DAY_OF_MONTH));
                builder.append("-");
                builder.append(cal.get(Calendar.MONTH));
                builder.append("-");
                builder.append(cal.get(Calendar.YEAR));
                builder.append("-");
                builder.append(cal.get(Calendar.HOUR_OF_DAY));
                builder.append("_");
                builder.append(cal.get(Calendar.MINUTE));
                try (BufferedWriter writer = new BufferedWriter(
                        new FileWriter(builder.toString() + "_data.json"))) {
                    writer.append(array.toString());
                } catch (IOException ex) {

                }
                System.out.println(builder.toString());
                count = 0;
                array = new JSONArray();
                if (dayOfMonth != cal.get(Calendar.DAY_OF_MONTH)) {
                    builder = new StringBuilder();
                    builder.append(cal.get(Calendar.DAY_OF_MONTH));
                    builder.append("-");
                    builder.append(cal.get(Calendar.MONTH));
                    builder.append("-");
                    builder.append(cal.get(Calendar.YEAR));
                    String dirName = builder.toString();
                    File newDir = new File("src/main/resources/" + dirName);
                    newDir.mkdir();

                    File files = new File("src/main/resources/");
                    for (File file : files.listFiles()) {
                        if (file.getName().endsWith(".json")) {
                            file.renameTo(new File("src/main/resources/" + dirName + file.getName()));
                            file.delete();
                        }
                    }

                    dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
                }
            }
        }
    } catch (IOException | InterruptedException ex) {
        Logger.getLogger(ControlGpioExample.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.imos.sample.pi.LedBlink.java

public void pythonTemperatureSensor() {

    try {//  w w w.jav a  2 s.  c o  m
        String cmd = "sudo python /home/pi/Adafruit_Python_DHT/examples/AdafruitDHT.py 11 4";
        int count = 0;
        JSONArray array = new JSONArray();
        int dayOfMonth = 0;
        cal.setTime(new Date());
        dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
        while (true) {
            Process p = Runtime.getRuntime().exec(cmd);
            p.waitFor();

            StringBuilder output = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                output.append(line);
            }
            String result = output.toString(), tempStr;
            double temp, humid;
            if (!result.trim().isEmpty()) {
                tempStr = result.substring(result.indexOf("Humid"));
                result = result.substring(result.indexOf("=") + 1, result.indexOf("C") - 1);
                temp = Double.parseDouble(result);
                result = tempStr;
                result = result.substring(result.indexOf("=") + 1, result.indexOf("%"));
                humid = Double.parseDouble(result);

                JSONObject data = new JSONObject();
                data.put("temp", temp);
                data.put("humid", humid);
                data.put("time", new Date().getTime());

                array.put(data);
            }

            Thread.sleep(60000);
            count++;
            if (count == 60) {
                Logger.getLogger(PiMainFile.class.getName()).log(Level.INFO, null, "");
                cal.setTime(new Date());
                StringBuilder builder = new StringBuilder();
                builder.append(cal.get(Calendar.DAY_OF_MONTH));
                builder.append("-");
                builder.append(cal.get(Calendar.MONTH));
                builder.append("-");
                builder.append(cal.get(Calendar.YEAR));
                builder.append("-");
                builder.append(cal.get(Calendar.HOUR_OF_DAY));
                builder.append("_");
                builder.append(cal.get(Calendar.MINUTE));
                try (BufferedWriter writer = new BufferedWriter(
                        new FileWriter(builder.toString() + "_data.json"))) {
                    writer.append(array.toString());
                } catch (IOException ex) {

                }
                System.out.println(builder.toString());
                count = 0;
                array = new JSONArray();
                if (dayOfMonth != cal.get(Calendar.DAY_OF_MONTH)) {
                    builder = new StringBuilder();
                    builder.append(cal.get(Calendar.DAY_OF_MONTH));
                    builder.append("-");
                    builder.append(cal.get(Calendar.MONTH));
                    builder.append("-");
                    builder.append(cal.get(Calendar.YEAR));
                    String dirName = builder.toString();
                    File newDir = new File("src/main/resources/" + dirName);
                    newDir.mkdir();

                    File files = new File("src/main/resources/");
                    for (File file : files.listFiles()) {
                        if (file.getName().endsWith(".json")) {
                            file.renameTo(new File("src/main/resources/" + dirName + file.getName()));
                            file.delete();
                        }
                    }

                    dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
                }
            }
        }
    } catch (IOException | InterruptedException ex) {
        Logger.getLogger(LedBlink.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.imos.sample.pi.MotionSensor.java

public void pythonTemperatureSensor() {

    try {/*from  w  w  w.  ja  va  2  s.com*/
        String cmd = "sudo python /home/pi/Adafruit_Python_DHT/examples/AdafruitDHT.py 11 4";
        int count = 0;
        JSONArray array = new JSONArray();
        int dayOfMonth = 0;
        cal.setTime(new Date());
        dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
        while (true) {
            Process p = Runtime.getRuntime().exec(cmd);
            p.waitFor();

            StringBuilder output = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                output.append(line);
            }
            String result = output.toString(), tempStr;
            double temp, humid;
            if (!result.trim().isEmpty()) {
                tempStr = result.substring(result.indexOf("Humid"));
                result = result.substring(result.indexOf("=") + 1, result.indexOf("C") - 1);
                temp = Double.parseDouble(result);
                result = tempStr;
                result = result.substring(result.indexOf("=") + 1, result.indexOf("%"));
                humid = Double.parseDouble(result);

                JSONObject data = new JSONObject();
                data.put("temp", temp);
                data.put("humid", humid);
                data.put("time", new Date().getTime());

                array.put(data);
            }

            Thread.sleep(60000);
            count++;
            if (count == 60) {
                Logger.getLogger(PiMainFile.class.getName()).log(Level.INFO, null, "");
                cal.setTime(new Date());
                StringBuilder builder = new StringBuilder();
                builder.append(cal.get(Calendar.DAY_OF_MONTH));
                builder.append("-");
                builder.append(cal.get(Calendar.MONTH));
                builder.append("-");
                builder.append(cal.get(Calendar.YEAR));
                builder.append("-");
                builder.append(cal.get(Calendar.HOUR_OF_DAY));
                builder.append("_");
                builder.append(cal.get(Calendar.MINUTE));
                try (BufferedWriter writer = new BufferedWriter(
                        new FileWriter(builder.toString() + "_data.json"))) {
                    writer.append(array.toString());
                } catch (IOException ex) {

                }
                System.out.println(builder.toString());
                count = 0;
                array = new JSONArray();
                if (dayOfMonth != cal.get(Calendar.DAY_OF_MONTH)) {
                    builder = new StringBuilder();
                    builder.append(cal.get(Calendar.DAY_OF_MONTH));
                    builder.append("-");
                    builder.append(cal.get(Calendar.MONTH));
                    builder.append("-");
                    builder.append(cal.get(Calendar.YEAR));
                    String dirName = builder.toString();
                    File newDir = new File("src/main/resources/" + dirName);
                    newDir.mkdir();

                    File files = new File("src/main/resources/");
                    for (File file : files.listFiles()) {
                        if (file.getName().endsWith(".json")) {
                            file.renameTo(new File("src/main/resources/" + dirName + file.getName()));
                            file.delete();
                        }
                    }

                    dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
                }
            }
        }
    } catch (IOException | InterruptedException ex) {
        Logger.getLogger(MotionSensor.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.imos.sample.pi.TemperatureSensor.java

public void pythonTemperatureSensor() {

    try {/*from  w ww .  ja  va  2  s . c o m*/
        String cmd = "sudo python /home/pi/Adafruit_Python_DHT/examples/AdafruitDHT.py 11 4";
        int count = 0;
        JSONArray array = new JSONArray();
        int dayOfMonth = 0;
        cal.setTime(new Date());
        dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
        while (true) {
            Process p = Runtime.getRuntime().exec(cmd);
            p.waitFor();

            StringBuilder output = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                output.append(line);
            }
            String result = output.toString(), tempStr;
            double temp, humid;
            if (!result.trim().isEmpty()) {
                tempStr = result.substring(result.indexOf("Humid"));
                result = result.substring(result.indexOf("=") + 1, result.indexOf("C") - 1);
                temp = Double.parseDouble(result);
                result = tempStr;
                result = result.substring(result.indexOf("=") + 1, result.indexOf("%"));
                humid = Double.parseDouble(result);

                JSONObject data = new JSONObject();
                data.put("temp", temp);
                data.put("humid", humid);
                data.put("time", new Date().getTime());

                array.put(data);
            }

            Thread.sleep(60000);
            count++;
            if (count == 60) {
                Logger.getLogger(PiMainFile.class.getName()).log(Level.INFO, null, "");
                cal.setTime(new Date());
                StringBuilder builder = new StringBuilder();
                builder.append(cal.get(Calendar.DAY_OF_MONTH));
                builder.append("-");
                builder.append(cal.get(Calendar.MONTH));
                builder.append("-");
                builder.append(cal.get(Calendar.YEAR));
                builder.append("-");
                builder.append(cal.get(Calendar.HOUR_OF_DAY));
                builder.append("_");
                builder.append(cal.get(Calendar.MINUTE));
                try (BufferedWriter writer = new BufferedWriter(
                        new FileWriter(builder.toString() + "_data.json"))) {
                    writer.append(array.toString());
                } catch (IOException ex) {

                }
                System.out.println(builder.toString());
                count = 0;
                array = new JSONArray();
                if (dayOfMonth != cal.get(Calendar.DAY_OF_MONTH)) {
                    builder = new StringBuilder();
                    builder.append(cal.get(Calendar.DAY_OF_MONTH));
                    builder.append("-");
                    builder.append(cal.get(Calendar.MONTH));
                    builder.append("-");
                    builder.append(cal.get(Calendar.YEAR));
                    String dirName = builder.toString();
                    File newDir = new File("src/main/resources/" + dirName);
                    newDir.mkdir();

                    File files = new File("src/main/resources/");
                    for (File file : files.listFiles()) {
                        if (file.getName().endsWith(".json")) {
                            file.renameTo(new File("src/main/resources/" + dirName + file.getName()));
                            file.delete();
                        }
                    }

                    dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
                }
            }
        }
    } catch (IOException | InterruptedException ex) {
        Logger.getLogger(TemperatureSensor.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:de.pdark.dsmp.ProxyDownload.java

/**
 * Do the download.//from   www  .  j  av a 2 s.  c o m
 * 
 * @throws IOException
 * @throws DownloadFailed
 */
public void download() throws IOException, DownloadFailed {
    if (!config.isAllowed(url)) {
        throw new DownloadFailed(
                "HTTP/1.1 " + HttpStatus.SC_FORBIDDEN + " Download denied by rule in DSMP config");
    }

    // If there is a status file in the cache, return it instead of trying it again
    // As usual with caches, this one is a key area which will always cause
    // trouble.
    // TODO There should be a simple way to get rid of the cached statuses
    // TODO Maybe retry a download after a certain time?
    File statusFile = new File(dest.getAbsolutePath() + ".status");
    if (statusFile.exists()) {
        try {
            FileReader r = new FileReader(statusFile);
            char[] buffer = new char[(int) statusFile.length()];
            int len = r.read(buffer);
            r.close();
            String status = new String(buffer, 0, len);
            throw new DownloadFailed(status);
        } catch (IOException e) {
            log.warn("Error writing 'File not found'-Status to " + statusFile.getAbsolutePath(), e);
        }
    }

    mkdirs();

    HttpClient client = new HttpClient();

    String msg = "";
    if (config.useProxy(url)) {
        Credentials defaultcreds = new UsernamePasswordCredentials(config.getProxyUsername(),
                config.getProxyPassword());
        AuthScope scope = new AuthScope(config.getProxyHost(), config.getProxyPort(), AuthScope.ANY_REALM);
        HostConfiguration hc = new HostConfiguration();
        hc.setProxy(config.getProxyHost(), config.getProxyPort());
        client.setHostConfiguration(hc);
        client.getState().setProxyCredentials(scope, defaultcreds);
        msg = "via proxy ";
    }
    log.info("Downloading " + msg + "to " + dest.getAbsolutePath());

    GetMethod get = new GetMethod(url.toString());
    get.setFollowRedirects(true);
    try {
        int status = client.executeMethod(get);

        log.info("Download status: " + status);
        if (0 == 1 && log.isDebugEnabled()) {
            Header[] header = get.getResponseHeaders();
            for (Header aHeader : header)
                log.debug(aHeader.toString().trim());
        }

        log.info("Content: " + valueOf(get.getResponseHeader("Content-Length")) + " bytes; "
                + valueOf(get.getResponseHeader("Content-Type")));

        if (status != HttpStatus.SC_OK) {
            // Remember "File not found"
            if (status == HttpStatus.SC_NOT_FOUND) {
                try {
                    FileWriter w = new FileWriter(statusFile);
                    w.write(get.getStatusLine().toString());
                    w.close();
                } catch (IOException e) {
                    log.warn("Error writing 'File not found'-Status to " + statusFile.getAbsolutePath(), e);
                }
            }
            throw new DownloadFailed(get);
        }

        File dl = new File(dest.getAbsolutePath() + ".new");
        OutputStream out = new BufferedOutputStream(new FileOutputStream(dl));
        IOUtils.copy(get.getResponseBodyAsStream(), out);
        out.close();

        File bak = new File(dest.getAbsolutePath() + ".bak");
        if (bak.exists())
            bak.delete();
        if (dest.exists())
            dest.renameTo(bak);
        dl.renameTo(dest);
    } finally {
        get.releaseConnection();
    }
}

From source file:io.manasobi.utils.FileUtils.java

/**
* ? ?? ? ?  .<br>//from w  ww.  j av  a2 s.com
* ? ? ? 
* 
* @param srcFile  ? ?
* @param destFile ? ?
* @return  enum ? Result.SUCCESS   Result.FAIL? 
*/
public static Result rename(String srcFile, String destFile) {

    Result result = Result.EMPTY;

    if (!existsFile(srcFile)) {
        return buildFailResult(result, srcFile + "  .");
    }

    if (existsFile(destFile)) {

        result = deleteFile(destFile);

        if (result == Result.FAIL) {
            return buildFailResult(result, destFile + "  ? ? ?");
        }
    }

    File file = new File(srcFile);

    if (!file.renameTo(new File(destFile))) {

        result = copyFile(srcFile, destFile, false);

        if (result == Result.SUCCESS) {

            result = deleteFile(srcFile);

            if (result == Result.FAIL) {
                deleteFile(destFile);
            }
        }

        return result;

    } else {

        return Result.SUCCESS;
    }
}

From source file:com.disney.opa.fhb.util.FacilityUtil.java

/**
 * This method is to rename the file with document id
 * /*  ww  w .ja  v a2 s . c  o m*/
 * @param document
 * @throws Exception
 */
public void renameSQDocumentOnServer(Document document, int productId) throws Exception {
    File originalFile = new File(document.getServerPath());
    String fileNameOnServer = getSQDocumentFileNameOnServer(document, productId);
    String serverPath = getSQDocumentServerPath(fileNameOnServer);
    File newFile = new File(serverPath);
    if (!originalFile.renameTo(newFile)) {
        throw new Exception("Rename file failed, originalFile: " + originalFile + ", newFile: " + newFile);
    }
    document.setFileNameOnServer(fileNameOnServer);
    document.setServerPath(serverPath);
}

From source file:de.huxhorn.sulky.blobs.impl.BlobRepositoryImplTest.java

@Test
public void validating() throws IOException, AmbiguousIdException {
    BlobRepositoryImpl instance = new BlobRepositoryImpl();
    instance.setValidating(true);//from   www. j a va 2  s.  com
    File baseDirectory = folder.newFolder("foo");
    instance.setBaseDirectory(baseDirectory);
    String id = instance.put(TEST_DATA.getBytes("UTF-8"));
    InputStream is = instance.get(id);
    try {
        assertEquals(TEST_DATA, IOUtils.toString(is, "UTF-8"));
    } finally {
        IOUtils.closeQuietly(is);
    }
    File dataParent = new File(baseDirectory, TEST_DATA_ID.substring(0, 2));
    File f1 = new File(dataParent, TEST_DATA_ID.substring(2));
    File f2 = new File(dataParent, WRONG_DATA_ID.substring(2));
    if (f1.renameTo(f2)) {
        if (logger.isDebugEnabled())
            logger.debug("Renamed {} to {}.", f1.getAbsolutePath(), f2.getAbsolutePath());
    }
    assertTrue(instance.contains(WRONG_DATA_ID));
    assertNull(instance.get(WRONG_DATA_ID));
    assertFalse(instance.contains(WRONG_DATA_ID));
}

From source file:com.disney.opa.fhb.util.FacilityUtil.java

/**
 * This method is to rename the file with document id
 * /*from  w ww .  j  a  v  a2s.  co m*/
 * @param document
 * @throws Exception
 */
public void renameFacilityDocumentOnServer(Document document) throws Exception {
    File originalFile = new File(document.getServerPath());
    String fileNameOnServer = getFacilityDocumentFileNameOnServer(document);
    String serverPath = getFacilityDocumentServerPath(fileNameOnServer);
    File newFile = new File(serverPath);
    if (!originalFile.renameTo(newFile)) {
        throw new Exception("Rename file failed, originalFile: " + originalFile + ", newFile: " + newFile);
    }
    document.setFileNameOnServer(fileNameOnServer);
    document.setServerPath(serverPath);
}