Example usage for java.io File getName

List of usage examples for java.io File getName

Introduction

In this page you can find the example usage for java.io File getName.

Prototype

public String getName() 

Source Link

Document

Returns the name of the file or directory denoted by this abstract pathname.

Usage

From source file:com.google.cloud.public_datasets.nexrad2.GcsUntar.java

public static void main(String[] args) throws Exception {
    String tarFile = "/Users/vlakshmanan/data/nexrad/2016%2F05%2F03%2FKAMA%2FNWS_NEXRAD_NXL2DP_KAMA_20160503090000_20160503095959.tar";
    // String tarFile = "gs://gcp-public-data-nexrad-l2/2016/05/03/KAMA/NWS_NEXRAD_NXL2DP_KAMA_20160503000000_20160503005959.tar";

    System.out.println("Reading " + tarFile);
    try (GcsUntar untar = GcsUntar.fromGcsOrLocal(tarFile)) {
        for (File f : untar.getFiles()) {
            System.out.println(f.getName());
        }/*www.j  a va 2 s  .co  m*/
    }
}

From source file:mobi.salesforce.client.upload.DemoFileUploader.java

public static void main(String args[]) throws Exception {
    DemoFileUploader fileUpload = new DemoFileUploader();
    File file = new File("/Users/Kong/Desktop/a.jpg");
    // Upload the file
    fileUpload.executeMultiPartRequest("http://localhost:8080/m2salesforce/resources/file/upload", file,
            file.getName(), "File Uploaded :: a.jpg");
}

From source file:Main.java

public static void main(String[] args) {
    File file = new File(args[0]);
    if (!file.exists()) {
        System.out.println(args[0] + " does not exist.");
        return;/* www.  j a  v  a 2s. c om*/
    }
    if (file.isFile() && file.canRead()) {
        System.out.println(file.getName() + " can be read from.");
    }
    if (file.isDirectory()) {
        System.out.println(file.getPath() + " is a directory containing...");
        String[] files = file.list();
        for (int i = 0; i < files.length; i++) {
            System.out.println(files[i]);
        }
    }
}

From source file:com.sangupta.nutz.PerformanceTestSuite.java

public static void main(String[] args) throws Exception {
    File dir = new File("src/test/resources/markdown");
    File[] files = dir.listFiles();

    for (File file : files) {
        if (file.getName().endsWith(".text")) {
            final String markup = FileUtils.readFileToString(file);

            String html = file.getAbsolutePath();
            html = html.replace(".text", ".html");
            html = FileUtils.readFileToString(new File(html));

            TestData testData = new TestData(markup, html);
            tests.add(testData);/*  w  ww . j av  a2 s.  co m*/
        }
    }

    TestResults nutz = runTests(new TestExecutor() {

        private MarkdownProcessor processor = new MarkdownProcessor();

        @Override
        public String convertMarkup(String markup) throws Exception {
            return processor.toHtml(markup);
        }

    });

    TestResults txtmark = runTests(new TestExecutor() {

        @Override
        public String convertMarkup(String markup) throws Exception {
            return Processor.process(markup);
        }

    });

    TestResults pegdown = runTests(new TestExecutor() {

        private PegDownProcessor processor = new PegDownProcessor();

        @Override
        public String convertMarkup(String markup) throws Exception {
            return processor.markdownToHtml(markup);
        }

    });

    System.out.println("\n\n\n\n\n");
    System.out.println("Nutz: " + nutz);
    System.out.println("Pegdown: " + pegdown);
    System.out.println("TextMark: " + txtmark);
}

From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step7aLearningDataProducer.java

@SuppressWarnings("unchecked")
public static void main(String[] args) throws IOException {
    String inputDir = args[0];/*  ww w. jav a  2  s  .c o m*/
    File outputDir = new File(args[1]);

    if (!outputDir.exists()) {
        outputDir.mkdirs();
    }

    Collection<File> files = IOHelper.listXmlFiles(new File(inputDir));

    // for generating ConvArgStrict use this
    String prefix = "no-eq_DescendingScoreArgumentPairListSorter";

    // for oversampling using graph transitivity properties use this
    //        String prefix = "generated_no-eq_AscendingScoreArgumentPairListSorter";

    Iterator<File> iterator = files.iterator();
    while (iterator.hasNext()) {
        File file = iterator.next();

        if (!file.getName().startsWith(prefix)) {
            iterator.remove();
        }
    }

    int totalGoldPairsCounter = 0;

    Map<String, Integer> goldDataDistribution = new HashMap<>();

    DescriptiveStatistics statsPerTopic = new DescriptiveStatistics();

    int totalPairsWithReasonSameAsGold = 0;

    DescriptiveStatistics ds = new DescriptiveStatistics();

    for (File file : files) {
        List<AnnotatedArgumentPair> argumentPairs = (List<AnnotatedArgumentPair>) XStreamTools.getXStream()
                .fromXML(file);

        int pairsPerTopicCounter = 0;

        String name = file.getName().replaceAll(prefix, "").replaceAll("\\.xml", "");

        PrintWriter pw = new PrintWriter(new File(outputDir, name + ".csv"), "utf-8");

        pw.println("#id\tlabel\ta1\ta2");

        for (AnnotatedArgumentPair argumentPair : argumentPairs) {
            String goldLabel = argumentPair.getGoldLabel();

            if (!goldDataDistribution.containsKey(goldLabel)) {
                goldDataDistribution.put(goldLabel, 0);
            }

            goldDataDistribution.put(goldLabel, goldDataDistribution.get(goldLabel) + 1);

            pw.printf(Locale.ENGLISH, "%s\t%s\t%s\t%s%n", argumentPair.getId(), goldLabel,
                    multipleParagraphsToSingleLine(argumentPair.getArg1().getText()),
                    multipleParagraphsToSingleLine(argumentPair.getArg2().getText()));

            pairsPerTopicCounter++;

            int sameInOnePair = 0;

            // get gold reason statistics
            for (AnnotatedArgumentPair.MTurkAssignment assignment : argumentPair.mTurkAssignments) {
                String label = assignment.getValue();

                if (goldLabel.equals(label)) {
                    sameInOnePair++;
                }
            }

            ds.addValue(sameInOnePair);
            totalPairsWithReasonSameAsGold += sameInOnePair;
        }

        totalGoldPairsCounter += pairsPerTopicCounter;
        statsPerTopic.addValue(pairsPerTopicCounter);

        pw.close();
    }

    System.out.println("Total reasons matching gold " + totalPairsWithReasonSameAsGold);
    System.out.println(ds);

    System.out.println("Total gold pairs: " + totalGoldPairsCounter);
    System.out.println(statsPerTopic);

    int totalPairs = 0;
    for (Integer pairs : goldDataDistribution.values()) {
        totalPairs += pairs;
    }
    System.out.println("Total pairs: " + totalPairs);
    System.out.println(goldDataDistribution);

}

From source file:Main.java

public static void main(String[] args) {
    File file = new File(args[0]);
    if (!file.exists()) {
        System.out.println(args[0] + " does not exist.");
        return;// www  . ja v  a2s . c o  m
    }
    if (!(file.isFile() && file.canRead())) {
        System.out.println(file.getName() + " cannot be read from.");
        return;
    }
    try {
        FileInputStream fis = new FileInputStream(file);
        char current;
        while (fis.available() > 0) {
            current = (char) fis.read();
            System.out.print(current);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:de.tudarmstadt.ukp.csniper.resbuild.stuff.FilterPipe.java

public static void main(String[] args) throws IOException {
    List<String> files = new ArrayList<String>();
    int i = 0;/*from ww w  .  j a v a  2 s . c  o  m*/
    for (File file : FileUtils.listFiles(new File(base), new String[] { "csv" }, true)) {
        String text = FileUtils.readFileToString(file, "UTF-8");
        files.add(StringUtils.substringBeforeLast(file.getName(), ".") + ".xml");
        if (StringUtils.containsAny(text, "")) {
            files.remove(StringUtils.substringBeforeLast(file.getName(), ".") + ".xml");
        }
        i++;
        if (i % 100 == 0) {
            System.out.println("ok:" + i);
        }
    }

    FileUtils.writeLines(new File("D:\\hadoop\\output\\BNC_new\\exclusions.txt"), "UTF-8", files);
}

From source file:edu.cuhk.hccl.TripRealRatingsApp.java

public static void main(String[] args) throws IOException {
    File dir = new File(args[0]);
    File outFile = new File(args[1]);
    outFile.delete();//from w  ww  . j a v  a 2 s. c  o m

    StringBuilder buffer = new StringBuilder();

    for (File file : dir.listFiles()) {
        List<String> lines = FileUtils.readLines(file, "UTF-8");
        String hotelID = file.getName().split("_")[1];
        String author = null;
        boolean noContent = false;
        for (String line : lines) {
            if (line.startsWith("<Author>")) {
                try {
                    author = line.split(">")[1].trim();
                } catch (ArrayIndexOutOfBoundsException e) {
                    System.out.println("[ERROR] An error occured on this line:");
                    System.out.println(line);
                    continue;
                }
            } else if (line.startsWith("<Content>")) { // ignore records if they have no content
                String content = line.split(">")[1].trim();
                if (content == null || content.equals(""))
                    noContent = true;
            } else if (line.startsWith("<Rating>")) {
                String[] rates = line.split(">")[1].trim().split("\t");

                if (noContent || rates.length != 8)
                    continue;

                // Change missing rating from -1 to 0
                for (int i = 0; i < rates.length; i++) {
                    if (rates[i].equals("-1"))
                        rates[i] = "0";
                }

                buffer.append(author + "\t");
                buffer.append(hotelID + "\t");

                // overall
                buffer.append(rates[0] + "\t");
                // location
                buffer.append(rates[3] + "\t");
                // room
                buffer.append(rates[2] + "\t");
                // service
                buffer.append(rates[6] + "\t");
                // value
                buffer.append(rates[1] + "\t");
                // cleanliness
                buffer.append(rates[4] + "\t");

                buffer.append("\n");
            }
        }

        // Write once for each file
        FileUtils.writeStringToFile(outFile, buffer.toString(), true);

        // Clear buffer
        buffer.setLength(0);
        System.out.printf("[INFO] Finished processing %s\n", file.getName());
    }
    System.out.println("[INFO] All processinig are finished!");
}

From source file:com.tonygalati.sprites.SpriteGenerator.java

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

    //        if (args.length != 3)
    //        {//  www.jav  a2 s  .  co  m
    //           System.out.print("Usage: com.tonygalati.sprites.SpriteGenerator {path to images} {margin between images in px} {output file}\n");
    //           System.out.print("Note: The max height should only be around 32,767px due to Microsoft GDI using a 16bit signed integer to store dimensions\n");
    //           System.out.print("going beyond this dimension is possible with this tool but the generated sprite image will not work correctly with\n");
    //           System.out.print("most browsers.\n\n");
    //           return;
    //        }

    //        Integer margin = Integer.parseInt(args[1]);
    Integer margin = Integer.parseInt("1");
    String spriteFile = "icons-" + RandomStringUtils.randomAlphanumeric(10) + ".png";
    SpriteCSSGenerator cssGenerator = new SpriteCSSGenerator();

    ClassLoader classLoader = SpriteGenerator.class.getClassLoader();
    URL folderPath = classLoader.getResource(NAIC_SMALL_ICON);
    if (folderPath != null) {
        File imageFolder = new File(folderPath.getPath());

        // Read images
        ArrayList<BufferedImage> imageList = new ArrayList<BufferedImage>();
        Integer yCoordinate = null;

        for (File f : imageFolder.listFiles()) {
            if (f.isFile()) {
                String fileName = f.getName();
                String ext = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());

                if (ext.equals("png")) {
                    System.out.println("adding file " + fileName);
                    BufferedImage image = ImageIO.read(f);
                    imageList.add(image);

                    if (yCoordinate == null) {
                        yCoordinate = 0;
                    } else {
                        yCoordinate += (image.getHeight() + margin);
                    }

                    // add to cssGenerator
                    cssGenerator.addSpriteCSS(fileName.substring(0, fileName.indexOf(".")), 0, yCoordinate);
                }
            }
        }

        // Find max width and total height
        int maxWidth = 0;
        int totalHeight = 0;

        for (BufferedImage image : imageList) {
            totalHeight += image.getHeight() + margin;

            if (image.getWidth() > maxWidth)
                maxWidth = image.getWidth();
        }

        System.out.format("Number of images: %s, total height: %spx, width: %spx%n", imageList.size(),
                totalHeight, maxWidth);

        // Create the actual sprite
        BufferedImage sprite = new BufferedImage(maxWidth, totalHeight, BufferedImage.TYPE_INT_ARGB);

        int currentY = 0;
        Graphics g = sprite.getGraphics();
        for (BufferedImage image : imageList) {
            g.drawImage(image, 0, currentY, null);
            currentY += image.getHeight() + margin;
        }

        System.out.format("Writing sprite: %s%n", spriteFile);
        ImageIO.write(sprite, "png", new File(spriteFile));
        File cssFile = cssGenerator.getFile(spriteFile);
        System.out.println(cssFile.getAbsolutePath() + " created");
    } else {
        System.err.println("Could not find folder: " + NAIC_SMALL_ICON);

    }

}

From source file:com.linkedin.pinot.perf.FilterOperatorBenchmark.java

public static void main(String[] args) throws Exception {
    String rootDir = args[0];//from  ww  w  .j  ava2 s.  co m
    File[] segmentDirs = new File(rootDir).listFiles();
    String query = args[1];
    AtomicInteger totalDocsMatched = new AtomicInteger(0);
    Pql2Compiler pql2Compiler = new Pql2Compiler();
    BrokerRequest brokerRequest = pql2Compiler.compileToBrokerRequest(query);
    List<Callable<Void>> segmentProcessors = new ArrayList<>();
    long[] timesSpent = new long[segmentDirs.length];
    for (int i = 0; i < segmentDirs.length; i++) {
        File indexSegmentDir = segmentDirs[i];
        System.out.println("Loading " + indexSegmentDir.getName());
        Configuration tableDataManagerConfig = new PropertiesConfiguration();
        List<String> invertedColumns = new ArrayList<>();
        FilenameFilter filter = new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".bitmap.inv");
            }
        };
        String[] indexFiles = indexSegmentDir.list(filter);
        for (String indexFileName : indexFiles) {
            invertedColumns.add(indexFileName.replace(".bitmap.inv", ""));
        }
        tableDataManagerConfig.setProperty(IndexLoadingConfigMetadata.KEY_OF_LOADING_INVERTED_INDEX,
                invertedColumns);
        IndexLoadingConfigMetadata indexLoadingConfigMetadata = new IndexLoadingConfigMetadata(
                tableDataManagerConfig);
        IndexSegmentImpl indexSegmentImpl = (IndexSegmentImpl) Loaders.IndexSegment.load(indexSegmentDir,
                ReadMode.heap, indexLoadingConfigMetadata);
        segmentProcessors
                .add(new SegmentProcessor(i, indexSegmentImpl, brokerRequest, totalDocsMatched, timesSpent));
    }
    ExecutorService executorService = Executors.newCachedThreadPool();
    for (int run = 0; run < 5; run++) {
        System.out.println("START RUN:" + run);
        totalDocsMatched.set(0);
        long start = System.currentTimeMillis();
        List<Future<Void>> futures = executorService.invokeAll(segmentProcessors);
        for (int i = 0; i < futures.size(); i++) {
            futures.get(i).get();
        }
        long end = System.currentTimeMillis();
        System.out.println("Total docs matched:" + totalDocsMatched + " took:" + (end - start));
        System.out.println("Times spent:" + Arrays.toString(timesSpent));
        System.out.println("END RUN:" + run);
    }
    System.exit(0);
}