List of usage examples for java.io File delete
public boolean delete()
From source file:com.heliosdecompiler.appifier.Appifier.java
public static void main(String[] args) throws Throwable { if (args.length == 0) { System.out.println("An input JAR must be specified"); return;/*from w w w. j a v a 2 s . c o m*/ } File in = new File(args[0]); if (!in.exists()) { System.out.println("Input not found"); return; } String outName = args[0]; outName = outName.substring(0, outName.length() - ".jar".length()) + "-appified.jar"; File out = new File(outName); if (out.exists()) { if (!out.delete()) { System.out.println("Could not delete out file"); return; } } try (ZipOutputStream outstream = new ZipOutputStream(new FileOutputStream(out)); ZipFile zipFile = new ZipFile(in)) { { ZipEntry systemHook = new ZipEntry("com/heliosdecompiler/appifier/SystemHook.class"); outstream.putNextEntry(systemHook); outstream.write(SystemHookDump.dump()); outstream.closeEntry(); } Enumeration<? extends ZipEntry> enumeration = zipFile.entries(); while (enumeration.hasMoreElements()) { ZipEntry next = enumeration.nextElement(); if (!next.isDirectory()) { ZipEntry result = new ZipEntry(next.getName()); outstream.putNextEntry(result); if (next.getName().endsWith(".class")) { byte[] classBytes = IOUtils.toByteArray(zipFile.getInputStream(next)); outstream.write(transform(classBytes)); } else { IOUtils.copy(zipFile.getInputStream(next), outstream); } outstream.closeEntry(); } } } }
From source file:fi.helsinki.cs.iot.kahvihub.KahviHub.java
public static void main(String[] args) throws InterruptedException { // create Options object Options options = new Options(); // add conf file option options.addOption("c", true, "config file"); CommandLineParser parser = new BasicParser(); CommandLine cmd;/*from w w w . j a v a 2 s . c om*/ try { cmd = parser.parse(options, args); String configFile = cmd.getOptionValue("c"); if (configFile == null) { Log.e(TAG, "The config file option was not provided"); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("d", options); System.exit(-1); } else { try { HubConfig hubConfig = ConfigurationFileParser.parseConfigurationFile(configFile); Path libdir = Paths.get(hubConfig.getLibdir()); if (hubConfig.isDebugMode()) { File dir = libdir.toFile(); if (dir.exists() && dir.isDirectory()) for (File file : dir.listFiles()) file.delete(); } final IotHubHTTPD server = new IotHubHTTPD(hubConfig.getPort(), libdir, hubConfig.getHost()); init(hubConfig); try { server.start(); } catch (IOException ioe) { Log.e(TAG, "Couldn't start server:\n" + ioe); System.exit(-1); } Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { server.stop(); Log.i(TAG, "Server stopped"); } }); while (true) { Thread.sleep(1000); } } catch (ConfigurationParsingException | IOException e) { System.out.println("1:" + e.getMessage()); Log.e(TAG, e.getMessage()); System.exit(-1); } } } catch (ParseException e) { System.out.println(e.getMessage()); Log.e(TAG, e.getMessage()); System.exit(-1); } }
From source file:com.cyphercove.dayinspace.desktop.AtlasGenerator.java
public static void main(String[] args) throws Exception { //Delete old pack File oldPackFile = new File(TARGET_DIR + "/" + Assets.MAIN_ATLAS + Assets.ATLAS_EXTENSION); if (oldPackFile.exists()) { System.out.println("Deleting old pack file"); oldPackFile.delete(); }//w ww. j av a2s .c o m //Delete old font files Collection<File> oldFontFiles = FileUtils.listFiles(new File(TARGET_DIR), new RegexFileFilter(".*\\.fnt"), TrueFileFilter.INSTANCE); for (File file : oldFontFiles) { System.out.println("Copying font file: " + file.getName()); FileUtils.deleteQuietly(file); } //Create PNGs for GIF frames GifProcessor gifProcessor = new GifProcessor(0.015f); ArrayList<FileProcessor.Entry> gifFrames = gifProcessor.process(SOURCE_DIR, SOURCE_DIR); //Pack them TexturePacker.Settings settings = new TexturePacker.Settings(); settings.atlasExtension = Assets.ATLAS_EXTENSION; TexturePacker.process(settings, SOURCE_DIR, TARGET_DIR, Assets.MAIN_ATLAS); //Copy over any fonts Collection<File> fontFiles = FileUtils.listFiles(new File(SOURCE_DIR), new RegexFileFilter(".*\\.fnt"), TrueFileFilter.INSTANCE); File destDir = new File(TARGET_DIR); for (File file : fontFiles) { System.out.println("Copying font file: " + file.getName()); FileUtils.copyFileToDirectory(file, destDir); } //Delete the GIF frames that were generated. for (File file : gifProcessor.getGeneratedFiles()) file.delete(); }
From source file:Empty.java
public static void main(String[] argv) { if (argv.length != 1) { // no progname in argv[0] System.err.println("usage: Empty dirname"); System.exit(1);//from w w w . j a v a2 s . c o m } File dir = new File(argv[0]); if (!dir.exists()) { System.out.println(argv[0] + " does not exist"); return; } String[] info = dir.list(); for (int i = 0; i < info.length; i++) { File n = new File(argv[0] + dir.separator + info[i]); if (!n.isFile()) // skip ., .., other directories too continue; System.out.println("removing " + n.getPath()); if (!n.delete()) System.err.println("Couldn't remove " + n.getPath()); } }
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();//from ww w.ja v a2 s .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:com.bluexml.tools.miscellaneous.Translate.java
/** * @param args/*from w w w. ja v a 2 s . c om*/ */ public static void main(String[] args) { System.out.println("Translate.main() 1"); Console console = System.console(); System.out.println("give path to folder that contains properties files"); Scanner scanIn = new Scanner(System.in); try { // TODO Auto-generated method stub String sWhatever; System.out.println("Translate.main() 2"); sWhatever = scanIn.nextLine(); System.out.println("Translate.main() 3"); System.out.println(sWhatever); File inDir = new File(sWhatever); FilenameFilter filter = new FilenameFilter() { public boolean accept(File arg0, String arg1) { return arg1.endsWith("properties"); } }; File[] listFiles = inDir.listFiles(filter); for (File file : listFiles) { prapareFileToTranslate(file, inDir); } System.out.println("please translate text files and press enter"); String readLine = scanIn.nextLine(); System.out.println("Translate.main() 4"); for (File file : listFiles) { File values = new File(file.getParentFile(), file.getName() + ".txt"); writeBackValues(values, file); values.delete(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { scanIn.close(); } }
From source file:MakeDirectories.java
public static void main(String[] args) { if (args.length < 1) usage();//from w w w .ja v a 2 s . co m if (args[0].equals("-r")) { if (args.length != 3) usage(); File old = new File(args[1]), rname = new File(args[2]); old.renameTo(rname); fileData(old); fileData(rname); return; // Exit main } int count = 0; boolean del = false; if (args[0].equals("-d")) { count++; del = true; } count--; while (++count < args.length) { File f = new File(args[count]); if (f.exists()) { System.out.println(f + " exists"); if (del) { System.out.println("deleting..." + f); f.delete(); } } else { // Doesn't exist if (!del) { f.mkdirs(); System.out.println("created " + f); } } fileData(f); } }
From source file:com.nohowdezign.gcpmanager.Main.java
public final static void main(String[] args) { //Remove old log, it does not need to be there anymore. File oldLog = new File("./CloudPrintManager.log"); if (oldLog.exists()) { oldLog.delete(); }//from w w w . j av a2 s. c o m //Create a file reader for the props file Reader propsStream = null; try { propsStream = new FileReader("./props.json"); } catch (FileNotFoundException e1) { e1.printStackTrace(); } PrintManagerProperties props = null; if (propsStream != null) { props = gson.fromJson(propsStream, PrintManagerProperties.class); } else { logger.error("Property file does not exist. Please create one."); } //Set the variables to what is in the props file String email = props.getEmail(); String password = props.getPassword(); String printerId = props.getPrinterId(); amountOfPagesPerPrintJob = props.getAmountOfPagesPerPrintJob(); timeRestraintsForPrinter = props.getTimeRestraintsForPrinter(); JobStorageManager.timeToKeepFileInDays = props.getTimeToKeepFileInDays(); //AuthenticationManager authenticationManager = new AuthenticationManager(); //authenticationManager.setPasswordToUse(props.getAdministrativePassword()); //authenticationManager.initialize(1337); //Start the authentication manager on port 1337 try { cloudPrint.connect(email, password, "cloudprintmanager-1.0"); } catch (CloudPrintAuthenticationException e) { logger.error(e.getMessage()); } //TODO: Get a working website ready //Thread adminConsole = new Thread(new HttpServer(80), "HttpServer"); //adminConsole.start(); Thread printJobManager = new Thread(new JobStorageManagerThread(), "JobStorageManager"); printJobManager.start(); try { if (System.getProperty("os.name").toLowerCase().startsWith("win")) { logger.error("Your operating system is not supported. Please switch to linux ya noob."); System.exit(1); } else { PrinterManager printerManager = new PrinterManager(cloudPrint); File cupsPrinterDir = new File("/etc/cups/ppd"); if (cupsPrinterDir.isDirectory() && cupsPrinterDir.canRead()) { for (File cupsPrinterPPD : cupsPrinterDir.listFiles()) { //Init all of the CUPS printers in the manager printerManager.initializePrinter(cupsPrinterPPD, cupsPrinterPPD.getName()); } } else { logger.error("Please run this with a higher access level."); System.exit(1); } } } catch (Exception e) { e.printStackTrace(); } while (true) { try { getPrintingJobs(printerId); } catch (Exception e) { e.printStackTrace(); } } }
From source file:br.com.asisprojetos.mailreport.Main.java
public static void main(String args[]) { logger.debug("Testando debug"); if (args.length < 2) { logger.error("Erro : Numero de parametros errados."); System.exit(1);//from w ww. j a v a2 s .c om } String dataIniProc = String.format("%s 00:00:00", args[0]); String dataFimProc = String.format("%s 23:59:59", args[1]); logger.debug("Data Inicial: {} , Data Final: {}", dataIniProc, dataFimProc); String mes = String.format("%s/%s", args[0].substring(5, 7), args[0].substring(0, 4)); ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Datasource.xml"); TBRelatorioEmailDAO tbRelatorioEmailDAO = (TBRelatorioEmailDAO) context.getBean("TBRelatorioEmailDAO"); List<TBRelatorioEmail> listaRelatorioEmail = tbRelatorioEmailDAO.getAll(); for (TBRelatorioEmail tbRelatorioEmail : listaRelatorioEmail) { logger.debug(" CodContrato: {}, CodProduto: {}", tbRelatorioEmail.getCodContrato(), tbRelatorioEmail.getCodProduto()); List<String> listaEmails = tbRelatorioEmailDAO.getListaEmails(tbRelatorioEmail.getCodContrato()); if (!listaEmails.isEmpty()) { logger.debug("Lista de Emails obtida : [{}] ", listaEmails); //List<String> listaCodProduto = Arrays.asList( StringUtils.split(tbRelatorioEmail.getCodProduto(), ';') ) ; List<String> listaCodProduto = new ArrayList<String>(); listaCodProduto.add("1");//Sped Fiscal logger.debug("Gerando Relatorio Geral de Consumo por Produto..."); List<String> fileNames = new ArrayList<String>(); String fileName; BarChartDemo barChartDemo = (BarChartDemo) context.getBean("BarChartDemo"); //fileName = barChartDemo.generateBarChartGraph(tbRelatorioEmail.getCodContrato()); //fileNames.add(fileName); fileNames = barChartDemo.generateBarChartGraph2(tbRelatorioEmail.getCodContrato()); String templateFile = null; for (String codProduto : listaCodProduto) { if (codProduto.equals(Produto.SPED_FISCAL.getCodProduto())) { logger.debug("Produto Codigo : {} ", codProduto); templateFile = "index6.html"; //grafico de diagnostico fileName = barChartDemo.generateDiagnosticGraph(tbRelatorioEmail.getCodContrato(), dataIniProc, dataFimProc); fileNames.add(fileName); //grafico de auditoria recorrente fileName = barChartDemo.generateRecurrentGraph(tbRelatorioEmail.getCodContrato(), dataIniProc, dataFimProc); fileNames.add(fileName); } else { logger.debug("Produto Codigo : {} no aceito para gerar grafico ", codProduto); } logger.debug("Enviando Email.............Produto Codigo : {}", codProduto); SendEmail sendEmail = (SendEmail) context.getBean("SendEmail"); sendEmail.enviar(listaEmails.toArray(new String[listaEmails.size()]), "Relatrio Mensal de Riscos Fiscais", templateFile, fileNames, mes, tbRelatorioEmail.getCodContrato()); //sendEmail.enviar( new String[]{"leandro.prates@asisprojetos.com.br","leandro.prates@gmail.com"} , // "Relatrio Mensal de Riscos Fiscais", templateFile, fileNames, mes, tbRelatorioEmail.getCodContrato() ); } //Remover todos os arquivos png gerado para o cliente Config config = (Config) context.getBean("Config"); for (String f : fileNames) { try { File file = new File(String.format("%s/%s", config.getOutDirectory(), f)); if (file.delete()) { logger.debug("Arquivo: [{}/{}] deletado com sucesso.", config.getOutDirectory(), f); } else { logger.error("Erro ao deletar o arquivo: [{}/{}]", config.getOutDirectory(), f); } } catch (Exception ex) { logger.error("Erro ao deletar o arquivo: [{}/{}] . Message {}", config.getOutDirectory(), f, ex); } } } } }
From source file:com.joliciel.talismane.terminology.Main.java
public static void main(String[] args) throws Exception { String termFilePath = null;/*from ww w .ja v a2 s . com*/ String outFilePath = null; Command command = Command.extract; int depth = -1; String databasePropertiesPath = null; String projectCode = null; Map<String, String> argMap = TalismaneConfig.convertArgs(args); String logConfigPath = argMap.get("logConfigFile"); if (logConfigPath != null) { argMap.remove("logConfigFile"); Properties props = new Properties(); props.load(new FileInputStream(logConfigPath)); PropertyConfigurator.configure(props); } Map<String, String> innerArgs = new HashMap<String, String>(); for (Entry<String, String> argEntry : argMap.entrySet()) { String argName = argEntry.getKey(); String argValue = argEntry.getValue(); if (argName.equals("command")) command = Command.valueOf(argValue); else if (argName.equals("termFile")) termFilePath = argValue; else if (argName.equals("outFile")) outFilePath = argValue; else if (argName.equals("depth")) depth = Integer.parseInt(argValue); else if (argName.equals("databaseProperties")) databasePropertiesPath = argValue; else if (argName.equals("projectCode")) projectCode = argValue; else innerArgs.put(argName, argValue); } if (termFilePath == null && databasePropertiesPath == null) throw new TalismaneException("Required argument: termFile or databasePropertiesPath"); if (termFilePath != null) { String currentDirPath = System.getProperty("user.dir"); File termFileDir = new File(currentDirPath); if (termFilePath.lastIndexOf("/") >= 0) { String termFileDirPath = termFilePath.substring(0, termFilePath.lastIndexOf("/")); termFileDir = new File(termFileDirPath); termFileDir.mkdirs(); } } long startTime = new Date().getTime(); try { TerminologyServiceLocator terminologyServiceLocator = TerminologyServiceLocator.getInstance(); TerminologyService terminologyService = terminologyServiceLocator.getTerminologyService(); TerminologyBase terminologyBase = null; if (projectCode == null) throw new TalismaneException("Required argument: projectCode"); File file = new File(databasePropertiesPath); FileInputStream fis = new FileInputStream(file); Properties dataSourceProperties = new Properties(); dataSourceProperties.load(fis); terminologyBase = terminologyService.getPostGresTerminologyBase(projectCode, dataSourceProperties); if (command.equals(Command.analyse) || command.equals(Command.extract)) { if (depth < 0) throw new TalismaneException("Required argument: depth"); if (command.equals(Command.analyse)) { innerArgs.put("command", "analyse"); } else { innerArgs.put("command", "process"); } TalismaneFrench talismaneFrench = new TalismaneFrench(); TalismaneConfig config = new TalismaneConfig(innerArgs, talismaneFrench); PosTagSet tagSet = TalismaneSession.getPosTagSet(); Charset outputCharset = config.getOutputCharset(); TermExtractor termExtractor = terminologyService.getTermExtractor(terminologyBase); termExtractor.setMaxDepth(depth); termExtractor.setOutFilePath(termFilePath); termExtractor.getIncludeChildren().add(tagSet.getPosTag("P")); termExtractor.getIncludeChildren().add(tagSet.getPosTag("P+D")); termExtractor.getIncludeChildren().add(tagSet.getPosTag("CC")); termExtractor.getIncludeWithParent().add(tagSet.getPosTag("DET")); if (outFilePath != null) { if (outFilePath.lastIndexOf("/") >= 0) { String outFileDirPath = outFilePath.substring(0, outFilePath.lastIndexOf("/")); File outFileDir = new File(outFileDirPath); outFileDir.mkdirs(); } File outFile = new File(outFilePath); outFile.delete(); outFile.createNewFile(); Writer writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(outFilePath), outputCharset)); TermAnalysisWriter termAnalysisWriter = new TermAnalysisWriter(writer); termExtractor.addTermObserver(termAnalysisWriter); } Talismane talismane = config.getTalismane(); talismane.setParseConfigurationProcessor(termExtractor); talismane.process(); } else if (command.equals(Command.list)) { List<Term> terms = terminologyBase.getTermsByFrequency(2); for (Term term : terms) { LOG.debug("Term: " + term.getText()); LOG.debug("Frequency: " + term.getFrequency()); LOG.debug("Heads: " + term.getHeads()); LOG.debug("Expansions: " + term.getExpansions()); LOG.debug("Contexts: " + term.getContexts()); } } } finally { long endTime = new Date().getTime(); long totalTime = endTime - startTime; LOG.info("Total time: " + totalTime); } }