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:Main.java

public static void main(String[] args) throws Exception {
    Path newPath = FileSystems.getDefault().getPath("C:\\home\\docs\\");

    Files.delete(newPath);
    System.out.println("Directory deleted successfully!");
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Path p = Paths.get(new URI("file:///tmp.txt"));
    System.out.println(p);//from   w w  w  . j  a v  a2  s.  c  o m
    Files.delete(p);
}

From source file:Main.java

public static void main(String[] args) {

    Path path = FileSystems.getDefault().getPath("C:/tutorial/photos", "Demo.jpg");

    //delete the  file
    try {//from  ww  w  . j  a v a 2 s  . co  m
        Files.delete(path);
    } catch (IOException | SecurityException e) {
        System.err.println(e);
    }

}

From source file:Test.java

public static void main(String[] args) throws Exception {
    Path newFile = FileSystems.getDefault().getPath("C:\\home\\docs\\users.txt");
    Files.createFile(newFile);/*  ww w .  j a  v a  2 s.  c  o  m*/
    System.out.println("File created successfully!");

    Files.delete(newFile);
    System.out.println("File deleted successfully!");

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Path p = Paths.get("C:\\Java_Dev\\test1.txt");

    try {//from w w  w .ja v  a  2 s . c o  m
        Files.delete(p);
        System.out.println(p + "  deleted successfully.");
    } catch (NoSuchFileException e) {
        System.out.println(p + "  does  not  exist.");
    } catch (DirectoryNotEmptyException e) {
        System.out.println("Directory " + p + "  is not  empty.");
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:edu.jhu.hlt.concrete.ingesters.webposts.WebPostIngesterRunner.java

/**
 * @param args//from   w ww  .  j  a v  a  2 s  .  c o m
 */
public static void main(String... args) {
    Thread.setDefaultUncaughtExceptionHandler(new LoggedUncaughtExceptionHandler());
    WebPostIngesterRunner run = new WebPostIngesterRunner();
    JCommander jc = new JCommander(run, args);
    jc.setProgramName(WebPostIngesterRunner.class.getSimpleName());
    if (run.delegate.help) {
        jc.usage();
    }

    try {
        Path outpath = Paths.get(run.delegate.outputPath);
        IngesterParameterDelegate.prepare(outpath);
        WebPostIngester ing = new WebPostIngester();
        Path outWithExt = outpath.resolve("webposts.tar.gz");

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

        try (OutputStream os = Files.newOutputStream(outWithExt);
                GzipCompressorOutputStream gout = new GzipCompressorOutputStream(os);
                TarArchiver arch = new TarArchiver(gout)) {
            for (String pstr : run.delegate.paths) {
                LOGGER.debug("Running on file: {}", pstr);
                Path p = Paths.get(pstr);
                new ExistingNonDirectoryFile(p);
                try {
                    Communication next = ing.fromCharacterBasedFile(p);
                    arch.addEntry(new ArchivableCommunication(next));
                } catch (IngestException e) {
                    LOGGER.error("Error processing file: " + pstr, e);
                }
            }
        }
    } catch (NotFileException | IOException e) {
        LOGGER.error("Caught exception processing.", e);
    }
}

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

public static void main(String[] args) {

    // clean up from last run
    try {//from   w w  w . j a  va2 s  .  c  o  m
        Files.delete(Paths.get("loremipsum.html"));
        Files.delete(Paths.get("loremipsum.epub"));
    } catch (IOException e1) {
        /* no worries */ }

    try ( // read MarkDown
            FileReader fr = new FileReader("loremipsum.md");
            // and output HTML
            Writer fw = Files.newBufferedWriter(Paths.get("loremipsum.html"), StandardOpenOption.CREATE)) {

        // generate HTML from markdown
        MarkupParser parser = new MarkupParser();
        parser.setMarkupLanguage(new MarkdownLanguage());
        HtmlDocumentBuilder builder = new HtmlDocumentBuilder(fw);
        parser.setBuilder(builder);
        parser.parse(fr, true);

        // convert any inline equations in the HTML into MathML
        String html = new String(Files.readAllBytes(Paths.get("loremipsum.html")));
        StringBuffer sb = new StringBuffer();
        Matcher m = EQUATION.matcher(html);

        // for each equation
        while (m.find()) {
            // replace the LaTeX code with MathML
            m.appendReplacement(sb, laTeX2MathMl(m.group()));
        }
        m.appendTail(sb);

        // EPUB 2.0 can only handle embedded SVG so we find all referenced
        // SVG files and replace the reference with the actual SVG code
        Document parse = Jsoup.parse(sb.toString(), "UTF-8", Parser.xmlParser());

        Elements select = parse.select("img");
        for (Element element : select) {
            String attr = element.attr("src");
            if (attr.endsWith(".svg")) {
                byte[] svg = Files.readAllBytes(Paths.get(attr));
                element.html(new String(svg));
            }
        }

        // write back the modified HTML-file
        Files.write(Paths.get("loremipsum.html"), sb.toString().getBytes(), StandardOpenOption.WRITE);

        // instantiate a new EPUB version 2 publication
        Publication pub = Publication.getVersion2Instance();

        // include referenced resources (default is false)
        pub.setIncludeReferencedResources(true);

        // title and subject is required
        pub.addTitle("EclipseCon Demo");
        pub.addSubject("EclipseCon Demo");

        // generate table of contents (default is true)
        pub.setGenerateToc(true);
        epub.add(pub);

        // add one chapter
        pub.addItem(Paths.get("loremipsum.html").toFile());

        // create the EPUB
        epub.pack(new File("loremipsum.epub"));

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

}

From source file:edu.jhu.hlt.concrete.ingesters.bolt.BoltIngesterRunner.java

/**
 * @param args//w  w  w.j  a  v a  2 s.c o  m
 */
public static void main(String... args) {
    Thread.setDefaultUncaughtExceptionHandler(new LoggedUncaughtExceptionHandler());
    BoltIngesterRunner run = new BoltIngesterRunner();
    JCommander jc = new JCommander(run, args);
    jc.setProgramName(BoltIngesterRunner.class.getSimpleName());
    if (run.delegate.help) {
        jc.usage();
    }

    try {
        Path outpath = Paths.get(run.delegate.outputPath);
        IngesterParameterDelegate.prepare(outpath);
        BoltForumPostIngester ing = new BoltForumPostIngester();
        Path outWithExt = outpath.resolve("bolt.tar.gz");

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

        try (OutputStream os = Files.newOutputStream(outWithExt);
                GzipCompressorOutputStream gout = new GzipCompressorOutputStream(os);
                TarArchiver arch = new TarArchiver(gout)) {
            for (Path p : run.delegate.findFilesInPaths()) {
                LOGGER.debug("Running on file: {}", p);
                new ExistingNonDirectoryFile(p);
                try {
                    Communication next = ing.fromCharacterBasedFile(p);
                    arch.addEntry(new ArchivableCommunication(next));
                } catch (IngestException e) {
                    LOGGER.error("Error processing file: " + p, e);
                }
            }
        }
    } catch (NotFileException | IOException e) {
        LOGGER.error("Caught exception processing.", e);
    }
}

From source file:mcnutty.music.get.MusicGet.java

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

    //print out music-get
    System.out.println("                     _                      _   ");
    System.out.println(" _ __ ___  _   _ ___(_) ___       __ _  ___| |_ ");
    System.out.println("| '_ ` _ \\| | | / __| |/ __|____ / _` |/ _ \\ __|");
    System.out.println("| | | | | | |_| \\__ \\ | (_|_____| (_| |  __/ |_ ");
    System.out.println("|_| |_| |_|\\__,_|___/_|\\___|     \\__, |\\___|\\__|");
    System.out.println("                                 |___/          \n");

    //these will always be initialised later (but the compiler doesn't know that)
    String directory = "";
    Properties prop = new Properties();

    try (InputStream input = new FileInputStream("config.properties")) {
        prop.load(input);/* ww  w. j  a va 2  s.  c  o  m*/
        if (prop.getProperty("directory") != null) {
            directory = prop.getProperty("directory");
        } else {
            System.out.println(
                    "Error reading config property 'directory' - using default value of /tmp/musicserver/\n");
            directory = "/tmp/musicserver/";
        }
        if (prop.getProperty("password") == null) {
            System.out.println("Error reading config property 'password' - no default value, exiting\n");
            System.exit(1);
        }
    } catch (IOException e) {
        System.out.println("Error reading config file");
        System.exit(1);
    }

    //create a queue object
    ProcessQueue process_queue = new ProcessQueue();

    try {
        if (args.length > 0 && args[0].equals("clean")) {
            Files.delete(Paths.get("queue.json"));
        }
        //load an existing queue if possible
        String raw_queue = Files.readAllLines(Paths.get("queue.json")).toString();
        JSONArray queue_state = new JSONArray(raw_queue);
        ConcurrentLinkedQueue<QueueItem> loaded_queue = new ConcurrentLinkedQueue<>();
        JSONArray queue = queue_state.getJSONArray(0);
        for (int i = 0; i < queue.length(); i++) {
            JSONObject item = ((JSONObject) queue.get(i));
            QueueItem loaded_item = new QueueItem();
            loaded_item.ip = item.getString("ip");
            loaded_item.real_name = item.getString("name");
            loaded_item.disk_name = item.getString("guid");
            loaded_queue.add(loaded_item);
        }
        process_queue.bucket_queue = loaded_queue;
        System.out.println("Loaded queue from disk\n");
    } catch (Exception ex) {
        //otherwise clean out the music directory and start a new queue
        try {
            Files.walkFileTree(Paths.get(directory), new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    Files.delete(file);
                    return FileVisitResult.CONTINUE;
                }
            });
            Files.delete(Paths.get(directory));
        } catch (Exception e) {
            e.printStackTrace();
        }
        Files.createDirectory(Paths.get(directory));
        System.out.println("Created a new queue\n");
    }

    //start the web server
    StartServer start_server = new StartServer(process_queue, directory);
    new Thread(start_server).start();

    //wit for the web server to spool up
    Thread.sleep(1000);

    //read items from the queue and play them
    while (true) {
        QueueItem next_item = process_queue.next_item();
        if (!next_item.equals(new QueueItem())) {
            //Check the timeout
            int timeout = 547;
            try (FileInputStream input = new FileInputStream("config.properties")) {
                prop.load(input);
                timeout = Integer.parseInt(prop.getProperty("timeout", "547"));
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("Playing " + next_item.real_name);
            process_queue.set_played(next_item);
            process_queue.save_queue();
            Process p = Runtime.getRuntime().exec("timeout " + timeout
                    + "s mplayer -fs -quiet -af volnorm=2:0.25 " + directory + next_item.disk_name);

            try {
                p.waitFor(timeout, TimeUnit.SECONDS);
                Files.delete(Paths.get(directory + next_item.disk_name));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            process_queue.bucket_played.clear();
        }
        Thread.sleep(1000);
    }
}

From source file:edu.jhu.hlt.concrete.ingesters.alnc.ALNCIngesterRunner.java

/**
 * @param args//from  w w  w  . ja v  a 2 s  . c om
 */
public static void main(String... args) {
    Thread.setDefaultUncaughtExceptionHandler(new LoggedUncaughtExceptionHandler());
    ALNCIngesterRunner run = new ALNCIngesterRunner();
    JCommander jc = new JCommander(run, args);
    jc.setProgramName(ALNCIngesterRunner.class.getSimpleName());
    if (run.delegate.help) {
        jc.usage();
    }

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

        for (String pstr : run.delegate.paths) {
            LOGGER.debug("Running on file: {}", pstr);
            Path p = Paths.get(pstr);
            new ExistingNonDirectoryFile(p);
            Path outWithExt = outpath.resolve(p.getFileName() + ".tar.gz");

            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 (ALNCIngester ing = new ALNCIngester(p);
                    OutputStream os = Files.newOutputStream(outWithExt);
                    GzipCompressorOutputStream gout = new GzipCompressorOutputStream(os);
                    TarArchiver arch = new TarArchiver(gout)) {
                Iterator<Communication> iter = ing.iterator();
                while (iter.hasNext()) {
                    Communication c = iter.next();
                    LOGGER.debug("Got comm: {}", c.getId());
                    arch.addEntry(new ArchivableCommunication(c));
                }
            } catch (IngestException e) {
                LOGGER.error("Caught exception processing path: " + pstr, e);
            }
        }
    } catch (NotFileException | IOException e) {
        LOGGER.error("Caught exception processing.", e);
    }
}