Example usage for java.nio.file Files delete

List of usage examples for java.nio.file Files delete

Introduction

In this page you can find the example usage for java.nio.file Files delete.

Prototype

public static void delete(Path path) throws IOException 

Source Link

Document

Deletes a file.

Usage

From source file:org.eclipse.mylyn.docs.examples.ImproveFormatting.java

public static void main(String[] args) {
    try {//from www .  j  ava  2  s .co m
        // assign a working folder
        File workFolder = new File("work");

        // clean up from last run
        try {
            FileUtils.deleteQuietly(workFolder);
            Files.delete(Paths.get("new.epub"));
        } catch (IOException e1) {
            /* no worries */ }

        // first unpack the EPUB file we have
        epub.unpack(new File("Mastering Eclipse Plug-in Development.epub"), workFolder);

        // make note of the CSS file
        File cssFile = new File(workFolder, "OEBPS/epub.css");

        // delete the old CSS file
        cssFile.delete();

        // then copy in the modified CSS
        EPUBFileUtil.copy(new File("assets/epub.css"), cssFile);

        // find all the chapters, we know they start with "ch" 
        File oebps = new File(workFolder, "OEBPS");
        String[] list = oebps.list(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return name.startsWith("ch") && name.endsWith(".html");
            }

        });

        // and fix the code formatting
        for (String string : list) {
            File in = new File(oebps, string);
            improveCodeFormatting(in);
        }

        // add the Ubuntu monospace font
        Publication publication = epub.getOPSPublications().get(0);
        publication.addSubject("Demo");
        publication.addItem(new File("assets/UbuntuMono-B.ttf"));
        publication.addItem(new File("assets/UbuntuMono-BI.ttf"));
        publication.addItem(new File("assets/UbuntuMono-R.ttf"));
        publication.addItem(new File("assets/UbuntuMono-RI.ttf"));

        // and lastly we pack the EPUB again
        epub.pack(new File("new.epub"), workFolder);

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

From source file:edu.jhu.hlt.concrete.ingesters.annotatednyt.AnnotatedNYTIngesterRunner.java

/**
 * @param args//ww  w  .java  2 s . co  m
 */
public static void main(String... args) {
    Thread.setDefaultUncaughtExceptionHandler(new LoggedUncaughtExceptionHandler());
    AnnotatedNYTIngesterRunner run = new AnnotatedNYTIngesterRunner();
    JCommander jc = new JCommander(run, args);
    jc.setProgramName(AnnotatedNYTIngesterRunner.class.getSimpleName());
    if (run.delegate.help) {
        jc.usage();
    }

    try {
        Path outpath = Paths.get(run.delegate.outputPath);
        IngesterParameterDelegate.prepare(outpath);

        NYTCorpusDocumentParser parser = new NYTCorpusDocumentParser();
        for (String pstr : run.delegate.paths) {
            LOGGER.debug("Running on file: {}", pstr);
            Path p = Paths.get(pstr);
            new ExistingNonDirectoryFile(p);
            int nPaths = p.getNameCount();
            Path year = p.getName(nPaths - 2);
            Path outWithExt = outpath.resolve(year.toString() + p.getFileName());

            if (Files.exists(outWithExt)) {
                if (!run.delegate.overwrite) {
                    LOGGER.info("File: {} exists and overwrite disabled. Not running.", outWithExt.toString());
                    continue;
                } else {
                    Files.delete(outWithExt);
                }
            }

            try (InputStream is = Files.newInputStream(p);
                    BufferedInputStream bin = new BufferedInputStream(is);
                    TarGzArchiveEntryByteIterator iter = new TarGzArchiveEntryByteIterator(bin);

                    OutputStream os = Files.newOutputStream(outWithExt);
                    GzipCompressorOutputStream gout = new GzipCompressorOutputStream(os);
                    TarArchiver arch = new TarArchiver(gout)) {
                Iterable<byte[]> able = () -> iter;
                StreamSupport.stream(able.spliterator(), false).map(ba -> parser.fromByteArray(ba, false))
                        .map(doc -> new AnnotatedNYTDocument(doc))
                        .map(and -> new CommunicationizableAnnotatedNYTDocument(and).toCommunication())
                        .forEach(comm -> {
                            try {
                                arch.addEntry(new ArchivableCommunication(comm));
                            } catch (IOException e) {
                                LOGGER.error("Caught exception processing file: " + pstr, e);
                            }
                        });
            }
        }
    } catch (NotFileException | IOException e) {
        LOGGER.error("Caught exception processing.", e);
    }
}

From source file:org.apache.tika.eval.reports.ResultsReporter.java

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

    DefaultParser defaultCLIParser = new DefaultParser();
    CommandLine commandLine = null;//from w w  w.  ja va  2 s .  c o  m
    try {
        commandLine = defaultCLIParser.parse(OPTIONS, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        USAGE();
        return;
    }
    JDBCUtil dbUtil = null;
    if (commandLine.hasOption("db")) {
        Path db = Paths.get(commandLine.getOptionValue("db"));
        if (!H2Util.databaseExists(db)) {
            throw new RuntimeException("I'm sorry, but I couldn't find this h2 database: " + db
                    + "\nMake sure not to include the .mv.db at the end.");
        }
        dbUtil = new H2Util(db);
    } else if (commandLine.hasOption("jdbc")) {
        String driverClass = null;
        if (commandLine.hasOption("jdbcdriver")) {
            driverClass = commandLine.getOptionValue("jdbcdriver");
        }
        dbUtil = new JDBCUtil(commandLine.getOptionValue("jdbc"), driverClass);
    } else {
        System.err.println("Must specify either -db for the default in-memory h2 database\n"
                + "or -jdbc for a full jdbc connection string");
        USAGE();
        return;
    }
    try (Connection c = dbUtil.getConnection()) {
        Path tmpReportsFile = null;
        try {
            ResultsReporter resultsReporter = null;
            String reportsFile = commandLine.getOptionValue("rf");
            if (reportsFile == null) {
                tmpReportsFile = getDefaultReportsConfig(c);
                resultsReporter = ResultsReporter.build(tmpReportsFile);
            } else {
                resultsReporter = ResultsReporter.build(Paths.get(reportsFile));
            }

            Path reportsRootDirectory = Paths.get(commandLine.getOptionValue("rd", "reports"));
            if (Files.isDirectory(reportsRootDirectory)) {
                LOG.warn("'Reports' directory exists.  Will overwrite existing reports.");
            }

            resultsReporter.execute(c, reportsRootDirectory);
        } finally {
            if (tmpReportsFile != null) {
                Files.delete(tmpReportsFile);
            }
        }
    }
}

From source file:Main.java

public static FileVisitor<Path> getFileVisitor() {

    class DeleteDirVisitor extends SimpleFileVisitor<Path> {
        @Override/*from w  w w.  j  a  v  a2  s  . co m*/
        public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
            FileVisitResult result = FileVisitResult.CONTINUE;
            if (e != null) {
                System.out.format("Error deleting  %s.  %s%n", dir, e.getMessage());
                result = FileVisitResult.TERMINATE;
            } else {
                Files.delete(dir);
                System.out.format("Deleted directory  %s%n", dir);
            }
            return result;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Files.delete(file);
            System.out.format("Deleted file %s%n", file);
            return FileVisitResult.CONTINUE;
        }
    }
    FileVisitor<Path> visitor = new DeleteDirVisitor();
    return visitor;
}

From source file:dev.meng.wikipedia.profiler.Cleaner.java

public static void cleanData(List<String> values) {
    for (String value : values) {
        try {//from ww  w  .j  a va 2  s.  c  o  m
            Path filepath = Paths.get(value);
            File file = filepath.toFile();
            if (file.exists()) {
                if (file.isFile()) {
                    Files.delete(filepath);
                } else if (file.isDirectory()) {
                    FileUtils.deleteDirectory(file);
                }
            }
        } catch (IOException ex) {
            LogHandler.console(Cleaner.class, ex);
        }
    }
}

From source file:DeleteDirectory.java

@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
    System.out.println("Deleting " + file.getFileName());
    Files.delete(file);
    return FileVisitResult.CONTINUE;
}

From source file:com.yfiton.oauth.OAuthUtils.java

public static AuthorizationData readAuthorizationInfo(Path file)
        throws ConfigurationException, IOException, ClassNotFoundException {
    ObjectInputStream ois = new ObjectInputStream(Files.newInputStream(file));
    AuthorizationData data = (AuthorizationData) ois.readObject();
    ois.close();// w  w  w . j av a2  s  .com

    Files.delete(file);

    return data;
}

From source file:com.kixeye.chassis.bootstrap.TestUtils.java

public static OutputStream createFile(String path) {
    try {/*  w ww .j  a va2  s.  com*/
        Path p = Paths.get(SystemPropertyUtils.resolvePlaceholders(path));
        if (Files.exists(p)) {
            Files.delete(p);
        }
        File file = new File(path);
        if (!file.getParentFile().exists()) {
            if (!file.getParentFile().mkdirs()) {
                throw new RuntimeException("Unable to create parent file(s) " + file.getParent());
            }
        }
        return Files.newOutputStream(p);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.fizzed.stork.deploy.DeployHelper.java

static public void deleteRecursively(final Path path) throws IOException {
    if (!Files.exists(path)) {
        return;/*from w w w. j  a v  a 2s .  com*/
    }

    log.info("Deleting local {}", path);

    Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Files.delete(file);
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException ioe) throws IOException {
            Files.delete(dir);
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException ioe) throws IOException {
            return FileVisitResult.SKIP_SUBTREE;
        }
    });

    Files.deleteIfExists(path);
}

From source file:gui.CompressDecompress.java

public static byte[] compressBuffer(List<List<BigInteger>> encBuffer) {

    try {/*from  w ww  .  j  a va  2s.co  m*/
        File loc = new File("temp.dat");
        if (loc.exists()) {
            Files.delete(loc.toPath());
        }
        byte[] byteArray = serialize(encBuffer);
        AdaptiveArithmeticCompress.encoder(byteArray, loc.getAbsolutePath());

        InputStream is = new FileInputStream(loc);
        byte[] bytes = IOUtils.toByteArray(is);
        is.close();

        return bytes;

    } catch (IOException ex) {
        Logger.getLogger(CompressDecompress.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;

}