List of usage examples for java.io File getName
public String getName()
From source file:de.mirkosertic.invertedindex.core.FullIndexRun.java
public static void main(String[] args) throws IOException { InvertedIndex theIndex = new InvertedIndex(); UpdateIndexHandler theIndexHandler = new UpdateIndexHandler(theIndex); Tokenizer theTokenizer = new Tokenizer(new ToLowercaseTokenHandler(theIndexHandler)); File theOrigin = new File("/home/sertic/ownCloud/Textcontent"); for (File theFile : theOrigin.listFiles()) { System.out.println("Indexing " + theFile); String theFileContent = IOUtils.toString(new FileReader(theFile)); theTokenizer.process(new Document(theFile.getName(), theFileContent)); }/*from w ww. j a va 2 s .c o m*/ System.out.println(theIndex.getTokenCount() + " unique postings"); System.out.println(theIndex.getDocumentCount() + " documents"); theIndex.postings.entrySet().stream() .sorted((o1, o2) -> ((Integer) o1.getValue().getOccoursInDocuments().size()) .compareTo(o2.getValue().getOccoursInDocuments().size())) .forEach(t -> { System.out.println(t.getKey() + " -> " + t.getValue().getOccoursInDocuments().size()); }); System.out.println("Query"); Result theResult = theIndex.query(new TokenSequenceQuery(new String[] { "introduction", "to", "aop" })); System.out.println(theResult.getSize()); for (int i = 0; i < theResult.getSize(); i++) { System.out.println(theResult.getDoc(i).getName()); System.out.println(theIndex.rebuildContentFor(theResult.getDoc(i))); } long theCount = 100000; long theStart = System.currentTimeMillis(); for (int i = 0; i < theCount; i++) { theResult = theIndex.query(new TokenSequenceQuery(new String[] { "introduction", "to", "aop" })); } double theDuration = System.currentTimeMillis() - theStart; System.out.println(theCount + " Queries took " + theDuration + "ms"); System.out.println(theDuration / theCount); while (true) { theResult = theIndex.query(new TokenSequenceQuery(new String[] { "introduction", "to", "aop" })); } }
From source file:edu.illinois.cs.cogcomp.ner.BenchmarkOutputParser.java
/** * This main method will take one required argument, idenfitying the file containing * the results. Optionally, "-single" may also be passed indicating it will extract * the F1 value for single token values only. * @param args//from w w w . j ava2 s .c o m * @throws IOException */ public static void main(String[] args) throws IOException { parseArgs(args); System.out.println("L1lr,L1t,L2lr,L2t,L1 token,L2 token,F1,F2"); for (File file : resultsfile.listFiles()) { if (file.getName().startsWith("L1r")) { File resultsfile = new File(file, "ner/results.out"); if (resultsfile.exists()) { try { Parameters p = parseFilename(file); String lines = FileUtils.readFileToString(resultsfile); // get the token level score. String tokenL2 = null, tokenL1 = null; Matcher matcher = l2tokenlevelpattern.matcher(lines); if (matcher.find()) tokenL2 = matcher.group(1); else { matcher = ol2tokenlevelpattern.matcher(lines); if (matcher.find()) tokenL2 = matcher.group(1); else System.err.println("No token level match"); } matcher = l1tokenlevelpattern.matcher(lines); if (matcher.find()) tokenL1 = matcher.group(1); else { matcher = ol1tokenlevelpattern.matcher(lines); if (matcher.find()) tokenL1 = matcher.group(1); else System.err.println("No token level match"); } matcher = phraselevelpattern.matcher(lines); matcher.find(); String phraseL1 = matcher.group(1); String phraseL2 = matcher.group(2); System.out.println( p.toString() + "," + tokenL1 + "," + tokenL2 + "," + phraseL1 + "," + phraseL2); } catch (java.lang.IllegalStateException ise) { System.err.println("The results file could not be parsed : \"" + resultsfile + "\""); } } else { System.err.println("no results in " + resultsfile); } } } }
From source file:edu.cuhk.hccl.IDConverter.java
public static void main(String[] args) { if (args.length < 2) { printUsage();/*from w w w . ja va 2 s . c o m*/ } try { File inFile = new File(args[0]); File outFile = new File(args[1]); if (inFile.isDirectory()) { System.out.println("ID Converting begins..."); FileUtils.forceMkdir(outFile); for (File file : inFile.listFiles()) { if (!file.isHidden()) processFile(file, new File(outFile.getAbsolutePath() + "/" + FilenameUtils.removeExtension(file.getName()) + "-long.txt")); } } else if (inFile.isFile()) { System.out.println("ID Converting begins..."); processFile(inFile, outFile); } else { printUsage(); } System.out.println("ID Converting finished."); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.px100systems.data.utility.RestoreUtility.java
public static void main(String[] args) { if (args.length < 3) { System.err.println("Usage: java -cp ... com.px100systems.data.utility.RestoreUtility " + "<springXmlConfigFile> <persisterBeanName> <backupDirectory> [compare]"); return;//from w ww . j a va 2 s. c o m } FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext("file:" + args[0]); try { PersistenceProvider persister = ctx.getBean(args[1], PersistenceProvider.class); File directory = new File(args[2]); if (!directory.isDirectory()) { System.err.println(directory.getName() + " is not a directory"); return; } List<File> files = new ArrayList<File>(); //noinspection ConstantConditions for (File file : directory.listFiles()) if (BackupFile.isBackup(file)) files.add(file); if (files.isEmpty()) { System.err.println(directory.getName() + " directory has no backup files"); return; } if (args.length == 4 && args[3].equalsIgnoreCase("compare")) { final Map<String, Map<Long, RawRecord>> units = new HashMap<String, Map<Long, RawRecord>>(); for (String storage : persister.storage()) { System.out.println("Storage " + storage); persister.loadByStorage(storage, new PersistenceProvider.LoadCallback() { @Override public void process(RawRecord record) { Map<Long, RawRecord> unitList = units.get(record.getUnitName()); if (unitList == null) { unitList = new HashMap<Long, RawRecord>(); units.put(record.getUnitName(), unitList); } unitList.put(record.getId(), record); } }); for (final Map.Entry<String, Map<Long, RawRecord>> unit : units.entrySet()) { BackupFile file = null; for (int i = 0, n = files.size(); i < n; i++) if (BackupFile.isBackup(files.get(i), unit.getKey())) { file = new BackupFile(files.get(i)); files.remove(i); break; } if (file == null) throw new RuntimeException("Could not find backup file for unit " + unit.getKey()); final Long[] count = new Long[] { 0L }; file.read(new PersistenceProvider.LoadCallback() { @Override public void process(RawRecord record) { RawRecord r = unit.getValue().get(record.getId()); if (r == null) throw new RuntimeException("Could not find persisted record " + record.getId() + " for unit " + unit.getKey()); if (!r.equals(record)) throw new RuntimeException( "Record " + record.getId() + " mismatch for unit " + unit.getKey()); count[0] = count[0] + 1; } }); if (count[0] != unit.getValue().size()) throw new RuntimeException("Extra persisted records for unit " + unit.getKey()); System.out.println(" Unit " + unit.getKey() + ": OK"); } units.clear(); } if (!files.isEmpty()) { System.err.println("Extra backups: "); for (File file : files) System.err.println(" " + file.getName()); } } else { persister.init(); for (File file : files) { InMemoryDatabase.readBackupFile(file, persister); System.out.println("Loaded " + file.getName()); } } } catch (Exception e) { throw new RuntimeException(e); } finally { ctx.close(); } }
From source file:apps.classification.ClassifySVMPerf.java
public static void main(String[] args) throws IOException { boolean dumpConfidences = false; String cmdLineSyntax = ClassifySVMPerf.class.getName() + " [OPTIONS] <path to svm_perf_classify> <testIndexDirectory> <modelDirectory>"; Options options = new Options(); OptionBuilder.withArgName("d"); OptionBuilder.withDescription("Dump confidences file"); OptionBuilder.withLongOpt("d"); OptionBuilder.isRequired(false);//w w w .ja v a 2 s . c o m OptionBuilder.hasArg(false); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("t"); OptionBuilder.withDescription("Path for temporary files"); OptionBuilder.withLongOpt("t"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("v"); OptionBuilder.withDescription("Verbose output"); OptionBuilder.withLongOpt("v"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(false); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("s"); OptionBuilder.withDescription("Don't delete temporary training file in svm_perf format (default: delete)"); OptionBuilder.withLongOpt("s"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(false); options.addOption(OptionBuilder.create()); SvmPerfClassifierCustomizer customizer = null; GnuParser parser = new GnuParser(); String[] remainingArgs = null; try { CommandLine line = parser.parse(options, args); remainingArgs = line.getArgs(); customizer = new SvmPerfClassifierCustomizer(remainingArgs[0]); if (line.hasOption("d")) dumpConfidences = true; if (line.hasOption("v")) customizer.printSvmPerfOutput(true); if (line.hasOption("s")) { customizer.setDeleteTestFiles(false); customizer.setDeletePredictionsFiles(false); } if (line.hasOption("t")) customizer.setTempPath(line.getOptionValue("t")); } catch (Exception exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(cmdLineSyntax, options); System.exit(-1); } if (remainingArgs.length != 3) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(cmdLineSyntax, options); System.exit(-1); } String testFile = remainingArgs[1]; File file = new File(testFile); String testName = file.getName(); String testPath = file.getParent(); String classifierFile = remainingArgs[2]; file = new File(classifierFile); String classifierName = file.getName(); String classifierPath = file.getParent(); FileSystemStorageManager storageManager = new FileSystemStorageManager(testPath, false); storageManager.open(); IIndex test = TroveReadWriteHelper.readIndex(storageManager, testName, TroveContentDBType.Full, TroveClassificationDBType.Full); storageManager.close(); SvmPerfDataManager dataManager = new SvmPerfDataManager(customizer); storageManager = new FileSystemStorageManager(classifierPath, false); storageManager.open(); SvmPerfClassifier classifier = (SvmPerfClassifier) dataManager.read(storageManager, classifierName); storageManager.close(); classifier.setRuntimeCustomizer(customizer); // CLASSIFICATION String classificationName = testName + "_" + classifierName; Classifier classifierModule = new Classifier(test, classifier, dumpConfidences); classifierModule.setClassificationMode(ClassificationMode.PER_CATEGORY); classifierModule.exec(); IClassificationDB testClassification = classifierModule.getClassificationDB(); storageManager = new FileSystemStorageManager(testPath, false); storageManager.open(); TroveReadWriteHelper.writeClassification(storageManager, testClassification, classificationName + ".cla", true); storageManager.close(); if (dumpConfidences) { ClassificationScoreDB confidences = classifierModule.getConfidences(); ClassificationScoreDB.write(testPath + Os.pathSeparator() + classificationName + ".confidences", confidences); } }
From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step3HITCreator.java
@SuppressWarnings("unchecked") public static void main(String[] args) throws IOException { String inputDir = args[0];/*from w w w. j a v a 2s. c o m*/ File outputDir = new File(args[1]); // sandbox or real MTurk? final boolean useSandbox = false; // required only for pilot // final int randomArgumentPairsCount = 50; // pseudo-random generator final Random random = new Random(1); for (Map.Entry<String, SortedSet<String>> entry : BATCHES.entrySet()) { Step3HITCreator hitCreator = new Step3HITCreator(useSandbox); hitCreator.outputPath = new File(outputDir, entry.getKey()); hitCreator.initialize(); // we will process only a subset first List<ArgumentPair> allArgumentPairs = new ArrayList<>(); Collection<File> files = IOHelper.listXmlFiles(new File(inputDir)); System.out.println(files); // read all files for the given batch for (File file : files) { if (entry.getValue().contains(file.getName())) { allArgumentPairs.addAll((List<ArgumentPair>) XStreamTools.getXStream().fromXML(file)); } } // we have to shuffle them Collections.shuffle(allArgumentPairs, random); // only for pilot // List<ArgumentPair> selectedArgumentPairs = allArgumentPairs // .subList(0, randomArgumentPairsCount); // for (ArgumentPair argumentPair : selectedArgumentPairs) { for (ArgumentPair argumentPair : allArgumentPairs) { hitCreator.process(argumentPair); } hitCreator.collectionProcessComplete(); } }
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 www . j av a 2s .c o 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:net.sf.vntconverter.VntConverter.java
/** * Fhrt den VntConverter mit den angegebnen Optionen aus. */// w w w . j a v a 2 s .com public static void main(String[] args) { try { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { // Wenn nicht, dann nicht ... } JFileChooser fileChooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("Text files (txt) and memo files (vnt)", "txt", "vnt"); fileChooser.setCurrentDirectory(new java.io.File(".")); fileChooser.setDialogTitle("Choose files to convert ..."); fileChooser.setFileFilter(filter); fileChooser.setMultiSelectionEnabled(true); if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { JFileChooser directoryChooser = new JFileChooser(); directoryChooser.setCurrentDirectory(new java.io.File(".")); directoryChooser.setDialogTitle("Choose target directory ..."); directoryChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); directoryChooser.setAcceptAllFileFilterUsed(false); if (directoryChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { VntConverter converter = new VntConverter(); String targetDirectoy = directoryChooser.getSelectedFile().getAbsolutePath(); System.out.println(targetDirectoy); for (File file : fileChooser.getSelectedFiles()) { if (file.getName().endsWith(".txt")) { converter.encode(file, new File(targetDirectoy + "\\" + file.getName().replace(".txt", ".vnt"))); } else if (file.getName().endsWith(".vnt")) { converter.decode(file, new File(targetDirectoy + "\\" + file.getName().replace(".vnt", ".txt"))); } } } } } catch (Exception e) { throw new RuntimeException("Exception caught", e); } }
From source file:org.bimserver.build.CreateGitHubRelease.java
public static void main(String[] args) { String username = args[0];/*from w ww.j a v a 2 s . c o m*/ String password = args[1]; String repo = args[2]; String project = args[3]; String tagname = args[4]; String name = args[5]; String body = args[6]; String draft = args[7]; String prerelease = args[8]; String filesString = args[9]; String[] filenames = filesString.split(";"); GitHubClient gitHubClient = new GitHubClient("api.github.com"); gitHubClient.setCredentials(username, password); Map<String, String> map = new HashMap<String, String>(); map.put("tag_name", tagname); // map.put("target_commitish", "test"); map.put("name", name); map.put("body", body); // map.put("draft", draft); // map.put("prerelease", prerelease); try { String string = "/repos/" + repo + "/" + project + "/releases"; System.out.println(string); JsonObject gitHubResponse = gitHubClient.post(string, map, JsonObject.class); System.out.println(gitHubResponse); String id = gitHubResponse.get("id").getAsString(); HttpHost httpHost = new HttpHost("uploads.github.com", 443, "https"); BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider(); basicCredentialsProvider.setCredentials(new AuthScope(httpHost), new UsernamePasswordCredentials(username, password)); HostnameVerifier hostnameVerifier = new AllowAllHostnameVerifier(); SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); CloseableHttpClient client = HttpClients.custom() .setDefaultCredentialsProvider(basicCredentialsProvider) .setHostnameVerifier((X509HostnameVerifier) hostnameVerifier).setSSLSocketFactory(sslsf) .build(); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(httpHost, basicAuth); HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(basicCredentialsProvider); context.setAuthCache(authCache); for (String filename : filenames) { File file = new File(filename); String url = "https://uploads.github.com/repos/" + repo + "/" + project + "/releases/" + id + "/assets?name=" + file.getName(); HttpPost post = new HttpPost(url); post.setHeader("Accept", "application/vnd.github.manifold-preview"); post.setHeader("Content-Type", "application/zip"); post.setEntity(new InputStreamEntity(new FileInputStream(file), file.length())); HttpResponse execute = client.execute(httpHost, post, context); execute.getEntity().getContent().close(); } } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } }
From source file:luisjosediez.Ejercicio2.java
/** * @param args the command line arguments *//* w w w. j a v a2 s . c o m*/ public static void main(String[] args) { // TODO code application logic here System.out.println("Introduce la direccin de un servidor ftp: "); FTPClient cliente = new FTPClient(); String servFTP = cadena(); String clave = ""; System.out.println("Introduce usuario (vaco para conexin annima): "); String usuario = cadena(); String opcion; if (usuario.equals("")) { clave = ""; } else { System.out.println("Introduce contrasea: "); clave = cadena(); } try { cliente.setPassiveNatWorkaround(false); cliente.connect(servFTP, 21); boolean login = cliente.login(usuario, clave); if (login) { System.out.println("Conexin ok"); } else { System.out.println("Login incorrecto"); cliente.disconnect(); System.exit(1); } do { System.out.println("Orden [exit para salir]: "); opcion = cadena(); if (opcion.equals("ls")) { FTPFile[] files = cliente.listFiles(); String tipos[] = { "Fichero", "Directorio", "Enlace" }; for (int i = 0; i < files.length; i++) { System.out.println("\t" + files[i].getName() + "\t=> " + tipos[files[i].getType()]); } } else if (opcion.startsWith("cd ")) { try { cliente.changeWorkingDirectory(opcion.substring(3)); } catch (IOException e) { } } else if (opcion.equals("help")) { System.out.println( "Puede ejecutar los comandos 'exit', 'ls', 'cd', 'get' y 'upload'. Para ms detalles utilice 'help <comando>'."); } else if (opcion.startsWith("help ")) { if (opcion.endsWith(" get")) { System.out.println( "Permite descargar un archivo concreto. Uso: 'get <rutaArchivoADescargar>'."); } else if (opcion.endsWith(" ls")) { System.out.println("Lista los ficheros y directorios en la ubicacin actual. Uso: 'ls'."); } else if (opcion.endsWith(" cd")) { System.out.println("Permite cambiar la ubicacin actual. Uso: 'cd <rutaDestino>'."); } else if (opcion.endsWith(" put")) { System.out.println( "Permite subir un archivo al directorio actual. Uso: 'put <rutaArchivoASubir>'."); } } else if (opcion.startsWith("get ")) { try { System.out.println("Indique la carpeta de descarga: "); try (FileOutputStream fos = new FileOutputStream(cadena() + opcion.substring(4))) { cliente.retrieveFile(opcion.substring(4), fos); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { } } else if (opcion.startsWith("put ")) { try { try { System.out.println(opcion.substring(4)); File local = new File(opcion.substring(4)); System.out.println(local.getName()); InputStream is = new FileInputStream(opcion.substring(4)); OutputStream os = cliente.storeFileStream(local.getName()); byte[] bytesIn = new byte[4096]; int read = 0; while ((read = is.read(bytesIn)) != -1) { os.write(bytesIn, 0, read); } is.close(); os.close(); boolean completed = cliente.completePendingCommand(); if (completed) { System.out.println("The file is uploaded successfully."); } } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { } } } while (!(opcion.equals("exit"))); boolean logout = cliente.logout(); if (logout) System.out.println("Logout..."); else System.out.println("Logout incorrecto"); cliente.disconnect(); } catch (Exception e) { e.printStackTrace(); } }