Example usage for org.apache.commons.io FileUtils copyFile

List of usage examples for org.apache.commons.io FileUtils copyFile

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils copyFile.

Prototype

public static void copyFile(File srcFile, File destFile) throws IOException 

Source Link

Document

Copies a file to a new location preserving the file date.

Usage

From source file:com.discursive.jccook.io.FileCopyExample.java

public static void main(String[] args) {
    try {//from  w  w w.java2  s .  c  om
        File src = new File("test.dat");
        File dest = new File("test.dat.bak");

        FileUtils.copyFile(src, dest);
    } catch (IOException ioe) {
        System.out.println("Problem copying file.");
    }

    try {
        File src = new File("test.dat");
        File dir = new File("./temp");

        FileUtils.copyFileToDirectory(src, dir);
    } catch (IOException ioe) {
        System.out.println("Problem copying file to dir.");
    }

    try {
        String string = "Blah blah blah";
        File dest = new File("test.tmp");

        FileUtils.writeStringToFile(dest, string, "ISO-8859-1");
    } catch (IOException ioe) {
        System.out.println("Error writing out a String.");
    }
}

From source file:mase.jbot.PresetCreator.java

public static void main(String[] args) throws Exception {
    if (args.length != 3) {
        System.out.println("PresetCreator [preset file] [controller file] [name tag]");
        System.exit(1);// w w  w .j a  v  a2s  .  c o m
    }

    File preset = new File(args[0]);
    File cont = new File(args[1]);
    File tag = new File(args[2]);

    PersistentSolution sol = SolutionPersistence.readSolution(new FileInputStream(cont));
    GroupController contr = sol.getController();
    if (contr instanceof HomogeneousGroupController) {
        AgentController ac = contr.getAgentControllers(1)[0];
        File newFile = new File(preset.getAbsolutePath().replace(".conf", "") + "-" + tag + ".conf");
        FileUtils.copyFile(preset, newFile);
        NEATAgentController nac = (NEATAgentController) ac;
        double[] w = NEATSerializer.serializeToArray(nac.getNetwork());
        fillWeights(newFile, w);
    } else {
        AgentController[] acs = contr.getAgentControllers(0);
        for (int i = 0; i < acs.length; i++) {
            File newFile = new File(
                    preset.getAbsolutePath().replace(".conf", "") + "-" + tag + "-" + i + ".conf");
            FileUtils.copyFile(preset, newFile);
            NEATAgentController nac = (NEATAgentController) acs[i];
            double[] w = NEATSerializer.serializeToArray(nac.getNetwork());
            fillWeights(newFile, w);
        }
    }
}

From source file:cc.gospy.example.basic.SeleniumDemo.java

public static void main(String[] args) {
    String phantomJsPath = "D:/Program Files/PhantomJS/phantomjs-2.1.1-windows/bin/phantomjs.exe";
    String savePath = "D:/screenshot.png";
    Gospy.custom().setScheduler(Schedulers.VerifiableScheduler.custom().setPendingTimeInSeconds(60).build())
            .addFetcher(Fetchers.TransparentFetcher.getDefault()).addProcessor(Processors.PhantomJSProcessor
                    .custom().setPhantomJsBinaryPath(phantomJsPath).setWebDriverExecutor((page, webDriver) -> {
                        TakesScreenshot screenshot = (TakesScreenshot) webDriver;
                        File src = screenshot.getScreenshotAs(OutputType.FILE);
                        FileUtils.copyFile(src, new File(savePath));
                        System.out.println("screenshot has been saved to " + savePath);
                        return new Result<>();
                    }).build())/*  ww w  . j  a  v  a2s  . c o  m*/
            .build().addTask("phantomjs://http://www.zhihu.com").start();
}

From source file:com.javacreed.examples.misc.Example.java

public static void main(final String[] args) throws Exception {
    final String link = "http://www.javacreed.com/";
    final File screenShot = new File("screenshot.png").getAbsoluteFile();

    Example.LOGGER.debug("Creating Firefox Driver");
    final WebDriver driver = new FirefoxDriver();
    try {//w ww  .ja v a  2  s. c  o m
        Example.LOGGER.debug("Opening page: {}", link);
        driver.get(link);

        Example.LOGGER.debug("Wait a bit for the page to render");
        TimeUnit.SECONDS.sleep(5);

        Example.LOGGER.debug("Taking Screenshot");
        final File outputFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(outputFile, screenShot);
        Example.LOGGER.debug("Screenshot saved: {}", screenShot);
    } finally {
        driver.close();
    }

    Example.LOGGER.debug("done");
}

From source file:akori.AKORI.java

public static void main(String[] args) throws IOException, InterruptedException {
    System.out.println("esto es AKORI");

    URL = "http://www.mbauchile.cl";
    PATH = "E:\\NetBeansProjects\\AKORI\\";
    NAME = "mbauchile.png";
    // Extrar DOM tree

    Document doc = Jsoup.connect(URL).timeout(0).get();

    // The Firefox driver supports javascript 
    WebDriver driver = new FirefoxDriver();
    driver.manage().window().maximize();
    System.out.println(driver.manage().window().getSize().toString());
    System.out.println(driver.manage().window().getPosition().toString());
    int xmax = driver.manage().window().getSize().width;
    int ymax = driver.manage().window().getSize().height;

    // Go to the URL page
    driver.get(URL);/*from w w w.  ja  v  a2 s  .com*/

    File screen = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(screen, new File(PATH + NAME));

    BufferedImage img = ImageIO.read(new File(PATH + NAME));
    //Graphics2D graph = img.createGraphics();

    BufferedImage img1 = new BufferedImage(xmax, ymax, BufferedImage.TYPE_INT_ARGB);
    Graphics2D graph1 = img.createGraphics();
    double[][] matrix = new double[ymax][xmax];
    BufferedReader in = new BufferedReader(new FileReader("et.txt"));
    String linea;
    double max = 0;
    graph1.drawImage(img, 0, 0, null);
    HashMap<String, Integer> lista = new HashMap<String, Integer>();
    int count = 0;
    for (int i = 0; (linea = in.readLine()) != null && i < 10000; ++i) {
        String[] datos = linea.split(",");
        int x = (int) Double.parseDouble(datos[0]);
        int y = (int) Double.parseDouble(datos[2]);
        long time = Double.valueOf(datos[4]).longValue();
        if (x >= xmax || y >= ymax)
            continue;
        if (time < 691215)
            continue;
        if (time > 705648)
            break;
        if (lista.containsKey(x + "," + y))
            lista.put(x + "," + y, lista.get(x + "," + y) + 1);
        else
            lista.put(x + "," + y, 1);
        ++count;
    }
    System.out.println(count);
    in.close();
    Iterator iter = lista.entrySet().iterator();
    Map.Entry e;
    for (String key : lista.keySet()) {
        Integer i = lista.get(key);
        if (max < i)
            max = i;
    }
    System.out.println(max);
    max = 0;
    while (iter.hasNext()) {
        e = (Map.Entry) iter.next();
        String xy = (String) e.getKey();
        String[] datos = xy.split(",");
        int x = Integer.parseInt(datos[0]);
        int y = Integer.parseInt(datos[1]);
        matrix[y][x] += (int) e.getValue();
        double aux;
        if ((aux = normalMatrix(matrix, y, x, ((int) e.getValue()) * 4)) > max) {
            max = aux;
        }
        //normalMatrix(matrix,x,y,20);
        if (matrix[y][x] > max)
            max = matrix[y][x];
    }
    int A, R, G, B, n;
    for (int i = 0; i < xmax; ++i) {
        for (int j = 0; j < ymax; ++j) {
            if (matrix[j][i] != 0) {
                n = (int) Math.round(matrix[j][i] * 100 / max);
                R = Math.round((255 * n) / 100);
                G = Math.round((255 * (100 - n)) / 100);
                B = 0;
                A = Math.round((255 * n) / 100);
                ;
                if (R > 255)
                    R = 255;
                if (R < 0)
                    R = 0;
                if (G > 255)
                    G = 255;
                if (G < 0)
                    G = 0;
                if (R < 50)
                    A = 0;
                graph1.setColor(new Color(R, G, B, A));
                graph1.fillOval(i, j, 1, 1);
            }
        }
    }
    //graph1.dispose();

    ImageIO.write(img, "png", new File("example.png"));
    System.out.println(max);

    graph1.setColor(Color.RED);
    // Extraer elementos
    Elements e1 = doc.body().getAllElements();
    int i = 1;
    ArrayList<String> tags = new ArrayList<String>();
    for (Element temp : e1) {

        if (tags.indexOf(temp.tagName()) == -1) {
            tags.add(temp.tagName());

            List<WebElement> query = driver.findElements(By.tagName(temp.tagName()));
            for (WebElement temp1 : query) {
                Point po = temp1.getLocation();
                Dimension d = temp1.getSize();
                if (d.width <= 0 || d.height <= 0 || po.x < 0 || po.y < 0)
                    continue;
                System.out.println(i + " " + temp.nodeName());
                System.out.println("  x: " + po.x + " y: " + po.y);
                System.out.println("  width: " + d.width + " height: " + d.height);
                graph1.draw(new Rectangle(po.x, po.y, d.width, d.height));
                ++i;
            }
        }
    }

    graph1.dispose();
    ImageIO.write(img, "png", new File(PATH + NAME));

    driver.quit();

}

From source file:com.textocat.textokit.postagger.opennlp.PackageModelZipAsArtifact.java

public static void main(String[] args) throws IOException {
    PackageModelZipAsArtifact cli = new PackageModelZipAsArtifact();
    new JCommander(cli, args);
    Path inputZipPath = Paths.get(cli.inputZipPathStr);
    if (!Files.isRegularFile(inputZipPath)) {
        System.err.println(inputZipPath + " is not an existing file.");
        System.exit(1);// www  .jav a  2  s. c om
    }
    POSModelJarManifestBean manifestBean = new POSModelJarManifestBean(cli.languageCode, cli.modelVariant);
    Path outputJarPath = inputZipPath
            .resolveSibling(FilenameUtils.getBaseName(inputZipPath.getFileName().toString()) + ".jar");
    try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(outputJarPath))) {
        JarOutputStream jout = new JarOutputStream(out, manifestBean.toManifest());
        jout.putNextEntry(new ZipEntry(ClasspathPOSModelHolder.getClassPath(manifestBean.getLanguageCode(),
                manifestBean.getModelVariant())));
        FileUtils.copyFile(inputZipPath.toFile(), jout);
        jout.closeEntry();
        jout.close();
    }
}

From source file:gov.nih.nci.caaersinstaller.util.CsmJaasFileCopier.java

public static void main(String args[]) throws Exception {

    //      File csmJaasTemplateFile = new File("/Users/Moni/temp/installer/postgres.csm_jaas.config");
    //      File csmJassConfigFile = new File("/Users/Moni/temp/installer/csm_jaas.config");

    File csmJaasTemplateFile = new File(args[0]);
    File csmJassConfigFile = new File(args[1]);

    if (csmJassConfigFile.exists()) {
        //append content of csmJaasTemplateFile to existing csmJaasConfigFile
        String csmJaasTemplateFileContent = FileUtils.readFileToString(csmJaasTemplateFile);
        StringBuilder stringBuilder = new StringBuilder(FileUtils.readFileToString(csmJassConfigFile));

        int start = stringBuilder.indexOf("caaers {");
        if (start != -1) {
            //If caaers context exisits then replace it.
            int end = stringBuilder.indexOf("};", start);
            end = end + 2;/*from  w ww.  j  a v  a  2 s. c  o  m*/
            stringBuilder.replace(start, end, csmJaasTemplateFileContent);
        } else {
            //if caaers context does not exist then add it 
            stringBuilder.append("\n");
            stringBuilder.append("\n");
            stringBuilder.append(csmJaasTemplateFileContent);
        }

        FileUtils.writeStringToFile(csmJassConfigFile, stringBuilder.toString());
        System.out.println("Modified csm_jaas.config to add caaers context");

    } else {
        //Create a new File with Contents of csmJaasTemplateFile
        FileUtils.copyFile(csmJaasTemplateFile, csmJassConfigFile);
        System.out.println("Created csm_jaas.config");

    }
}

From source file:mase.MaseEvolve.java

public static void main(String[] args) throws Exception {
    File outDir = getOutDir(args);
    boolean force = Arrays.asList(args).contains(FORCE);
    if (!outDir.exists()) {
        outDir.mkdirs();/*w  w w  .j a va 2s  . co  m*/
    } else if (!force) {
        System.out.println("Folder already exists: " + outDir.getAbsolutePath() + ". Waiting 5 sec.");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException ex) {
        }
    }

    // Get config file
    Map<String, String> pars = readParams(args);

    // Copy config to outdir
    try {
        File rawConfig = writeConfig(args, pars, outDir, false);
        File destiny = new File(outDir, DEFAULT_CONFIG);
        destiny.delete();
        FileUtils.moveFile(rawConfig, new File(outDir, DEFAULT_CONFIG));
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    // JBOT INTEGRATION: copy jbot config file to the outdir
    // Does nothing when jbot is not used
    if (pars.containsKey("problem.jbot-config")) {
        File jbot = new File(pars.get("problem.jbot-config"));
        FileUtils.copyFile(jbot, new File(outDir, jbot.getName()));
    }

    // Write config to system temp file
    File config = writeConfig(args, pars, outDir, true);
    // Launch
    launchExperiment(config);
}

From source file:ddf.metrics.reporting.internal.rrd4j.SampleDataGenerator.java

public static void main(String[] args) {
    if (args.length == 1) {
        try {/*  www  . j  a  va  2 s  .  c om*/
            String installLoc = args[0];
            File metricsDir = new File(installLoc, "/data/metrics");
            File[] files = metricsDir.listFiles();
            if (files != null) {
                for (File metricsFile : files) {
                    String metricsFileName = metricsFile.getName();
                    if (!metricsFileName.endsWith(".rrd")) {
                        continue;
                    }
                    RrdDb oldDb = new RrdDb(metricsFile.getAbsolutePath());
                    if (oldDb.getDsCount() > 1) {
                        continue;
                    }
                    DsType dsType = oldDb.getDatasource(0).getType();
                    String newDb = "target/" + metricsFileName;
                    long startTime = new DateTime().minusYears(1).getMillis();
                    int sampleSize = (int) ((new DateTime().getMillis() - startTime) / (60 * 1000));
                    new RrdMetricsRetrieverTest.RrdFileBuilder().rrdFileName(newDb).dsType(dsType)
                            .numSamples(sampleSize).numRows(sampleSize).startTime(startTime).build();
                    FileUtils.copyFile(new File(newDb), metricsFile);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    exit(0);
}

From source file:com.mycompany.webcrawler.GmailAutomation.java

public static void main(String[] args) {
    System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
    DesiredCapabilities dcaps = new DesiredCapabilities();

    dcaps.setCapability("takeScreenshot", true);
    //WebDriver driver = new PhantomJSDriver(dcaps);

    //Comment for PhantomJS
    ChromeDriver driver = new ChromeDriver();

    //Comment for PhantomJS
    //driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);

    driver.get(/*from w  w  w .  j ava  2  s.  c  o m*/
            "https://accounts.google.com/ServiceLogin?sacu=1&scc=1&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&osid=1&service=mail&ss=1&ltmpl=default&rm=false#identifier");

    try {
        Thread.sleep(2000);

        driver.findElement(By.id("Email")).sendKeys("Your gmail goes here");

        Thread.sleep(2000);
        driver.findElement(By.id("next")).click();

        Thread.sleep(2000);
        driver.findElement(By.id("Passwd")).sendKeys("Your password goes here");

        Thread.sleep(2000);
        driver.findElement(By.id("signIn")).click();

        Thread.sleep(2000);
        driver.findElement(By.xpath("//div[@class='T-I J-J5-Ji T-I-KE L3']")).click();

        Thread.sleep(2000);
        driver.findElement(By.className("vO")).sendKeys("Who you want to send the email to");

        Thread.sleep(2000);
        driver.findElement(By.className("aoT")).sendKeys("The subject");

        Thread.sleep(2000);
        driver.switchTo().activeElement().sendKeys(Keys.TAB);
        driver.switchTo().activeElement().sendKeys("The body");

        //Comment for PhantomJS
        //driver.findElement(By.xpath("//div[@class='Am Al editable LW-avf']")).sendKeys("Test Email");

        Thread.sleep(2000);
        File file = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(file, new File("screenshot.jpg"));

        Thread.sleep(2000);
        driver.findElement(By.xpath("//div[@class='T-I J-J5-Ji aoO T-I-atl L3']")).click();

        //Comment for PhantomJS
        //Thread.sleep(2000);
        //driver.get("https://mail.google.com/mail/u/0/#sent");
    } catch (IOException | InterruptedException | WebDriverException e) {
        System.out.println(e.getMessage());
    }
}