Example usage for java.io File length

List of usage examples for java.io File length

Introduction

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

Prototype

public long length() 

Source Link

Document

Returns the length of the file denoted by this abstract pathname.

Usage

From source file:Main.java

static public void main(String args[]) throws Exception {
    File infile = new File("inFilename");
    File outfile = new File("outFilename");

    RandomAccessFile inraf = new RandomAccessFile(infile, "r");
    RandomAccessFile outraf = new RandomAccessFile(outfile, "rw");

    FileChannel finc = inraf.getChannel();
    FileChannel foutc = outraf.getChannel();

    MappedByteBuffer inmbb = finc.map(FileChannel.MapMode.READ_ONLY, 0, (int) infile.length());

    Charset inCharset = Charset.forName("UTF8");
    Charset outCharset = Charset.forName("UTF16");

    CharsetDecoder inDecoder = inCharset.newDecoder();
    CharsetEncoder outEncoder = outCharset.newEncoder();

    CharBuffer cb = inDecoder.decode(inmbb);
    ByteBuffer outbb = outEncoder.encode(cb);

    foutc.write(outbb);//from w ww . j  a v a 2 s.c  o  m

    inraf.close();
    outraf.close();
}

From source file:com.shvet.poi.util.HexDump.java

public static void main(String[] args) throws Exception {
    File file = new File(args[0]);
    InputStream in = new BufferedInputStream(new FileInputStream(file));
    byte[] b = new byte[(int) file.length()];
    in.read(b);// w  ww .  java2s.co m
    System.out.println(HexDump.dump(b, 0, 0));
    in.close();
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    File file = new File("myimage.gif");
    FileInputStream fis = new FileInputStream(file);
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@//server.local:1521/prod", "scott",
            "tiger");
    conn.setAutoCommit(false);//from  w  ww  . j  av  a2 s .c o m
    PreparedStatement ps = conn.prepareStatement("insert into images values (?,?)");
    ps.setString(1, file.getName());
    ps.setBinaryStream(2, fis, (int) file.length());
    ps.executeUpdate();
    ps.close();
    fis.close();

}

From source file:omr.jai.TestImage3.java

public static void main(String[] args) {
        // Open the image (using the name passed as a command line parameter)
        PlanarImage pi = JAI.create("fileload", args[0]);

        // Get the image file size (non-JAI related).
        File image = new File(args[0]);
        System.out.println("Image file size: " + image.length() + " bytes.");

        print(pi);//w  ww  . j  a  v  a2s .  c  o  m
    }

From source file:com.twentyn.patentScorer.ScoreMerger.java

public static void main(String[] args) throws Exception {
    System.out.println("Starting up...");
    System.out.flush();//from   w w w  . j  a  va  2s  .  co  m
    Options opts = new Options();
    opts.addOption(Option.builder("h").longOpt("help").desc("Print this help message and exit").build());

    opts.addOption(Option.builder("r").longOpt("results").required().hasArg()
            .desc("A directory of search results to read").build());
    opts.addOption(Option.builder("s").longOpt("scores").required().hasArg()
            .desc("A directory of patent classification scores to read").build());
    opts.addOption(Option.builder("o").longOpt("output").required().hasArg()
            .desc("The output file where results will be written.").build());

    HelpFormatter helpFormatter = new HelpFormatter();
    CommandLineParser cmdLineParser = new DefaultParser();
    CommandLine cmdLine = null;
    try {
        cmdLine = cmdLineParser.parse(opts, args);
    } catch (ParseException e) {
        System.out.println("Caught exception when parsing command line: " + e.getMessage());
        helpFormatter.printHelp("DocumentIndexer", opts);
        System.exit(1);
    }

    if (cmdLine.hasOption("help")) {
        helpFormatter.printHelp("DocumentIndexer", opts);
        System.exit(0);
    }
    File scoresDirectory = new File(cmdLine.getOptionValue("scores"));
    if (cmdLine.getOptionValue("scores") == null || !scoresDirectory.isDirectory()) {
        LOGGER.error("Not a directory of score files: " + cmdLine.getOptionValue("scores"));
    }

    File resultsDirectory = new File(cmdLine.getOptionValue("results"));
    if (cmdLine.getOptionValue("results") == null || !resultsDirectory.isDirectory()) {
        LOGGER.error("Not a directory of results files: " + cmdLine.getOptionValue("results"));
    }

    FileWriter outputWriter = new FileWriter(cmdLine.getOptionValue("output"));

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

    FilenameFilter jsonFilter = new FilenameFilter() {
        public final Pattern JSON_PATTERN = Pattern.compile("\\.json$");

        public boolean accept(File dir, String name) {
            return JSON_PATTERN.matcher(name).find();
        }
    };

    Map<String, PatentScorer.ClassificationResult> scores = new HashMap<>();
    LOGGER.info("Reading scores from directory at " + scoresDirectory.getAbsolutePath());
    for (File scoreFile : scoresDirectory.listFiles(jsonFilter)) {
        BufferedReader reader = new BufferedReader(new FileReader(scoreFile));
        int count = 0;
        String line;
        while ((line = reader.readLine()) != null) {
            PatentScorer.ClassificationResult res = objectMapper.readValue(line,
                    PatentScorer.ClassificationResult.class);
            scores.put(res.docId, res);
            count++;
        }
        LOGGER.info("Read " + count + " scores from " + scoreFile.getAbsolutePath());
    }

    Map<String, List<DocumentSearch.SearchResult>> synonymsToResults = new HashMap<>();
    Map<String, List<DocumentSearch.SearchResult>> inchisToResults = new HashMap<>();
    LOGGER.info("Reading results from directory at " + resultsDirectory);
    // With help from http://stackoverflow.com/questions/6846244/jackson-and-generic-type-reference.
    JavaType resultsType = objectMapper.getTypeFactory().constructCollectionType(List.class,
            DocumentSearch.SearchResult.class);

    List<File> resultsFiles = Arrays.asList(resultsDirectory.listFiles(jsonFilter));
    Collections.sort(resultsFiles, new Comparator<File>() {
        @Override
        public int compare(File o1, File o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });
    for (File resultsFile : resultsFiles) {
        BufferedReader reader = new BufferedReader(new FileReader(resultsFile));
        CharBuffer buffer = CharBuffer.allocate(Long.valueOf(resultsFile.length()).intValue());
        int bytesRead = reader.read(buffer);
        LOGGER.info("Read " + bytesRead + " bytes from " + resultsFile.getName() + " (length is "
                + resultsFile.length() + ")");
        List<DocumentSearch.SearchResult> results = objectMapper.readValue(new CharArrayReader(buffer.array()),
                resultsType);

        LOGGER.info("Read " + results.size() + " results from " + resultsFile.getAbsolutePath());

        int count = 0;
        for (DocumentSearch.SearchResult sres : results) {
            for (DocumentSearch.ResultDocument resDoc : sres.getResults()) {
                String docId = resDoc.getDocId();
                PatentScorer.ClassificationResult classificationResult = scores.get(docId);
                if (classificationResult == null) {
                    LOGGER.warn("No classification result found for " + docId);
                } else {
                    resDoc.setClassifierScore(classificationResult.getScore());
                }
            }
            if (!synonymsToResults.containsKey(sres.getSynonym())) {
                synonymsToResults.put(sres.getSynonym(), new ArrayList<DocumentSearch.SearchResult>());
            }
            synonymsToResults.get(sres.getSynonym()).add(sres);
            count++;
            if (count % 1000 == 0) {
                LOGGER.info("Processed " + count + " search result documents");
            }
        }
    }

    Comparator<DocumentSearch.ResultDocument> resultDocumentComparator = new Comparator<DocumentSearch.ResultDocument>() {
        @Override
        public int compare(DocumentSearch.ResultDocument o1, DocumentSearch.ResultDocument o2) {
            int cmp = o2.getClassifierScore().compareTo(o1.getClassifierScore());
            if (cmp != 0) {
                return cmp;
            }
            cmp = o2.getScore().compareTo(o1.getScore());
            return cmp;
        }
    };

    for (Map.Entry<String, List<DocumentSearch.SearchResult>> entry : synonymsToResults.entrySet()) {
        DocumentSearch.SearchResult newSearchRes = null;
        // Merge all result documents into a single search result.
        for (DocumentSearch.SearchResult sr : entry.getValue()) {
            if (newSearchRes == null) {
                newSearchRes = sr;
            } else {
                newSearchRes.getResults().addAll(sr.getResults());
            }
        }
        if (newSearchRes == null || newSearchRes.getResults() == null) {
            LOGGER.error("Search results for " + entry.getKey() + " are null.");
            continue;
        }
        Collections.sort(newSearchRes.getResults(), resultDocumentComparator);
        if (!inchisToResults.containsKey(newSearchRes.getInchi())) {
            inchisToResults.put(newSearchRes.getInchi(), new ArrayList<DocumentSearch.SearchResult>());
        }
        inchisToResults.get(newSearchRes.getInchi()).add(newSearchRes);
    }

    List<String> sortedKeys = new ArrayList<String>(inchisToResults.keySet());
    Collections.sort(sortedKeys);
    List<GroupedInchiResults> orderedResults = new ArrayList<>(sortedKeys.size());
    Comparator<DocumentSearch.SearchResult> synonymSorter = new Comparator<DocumentSearch.SearchResult>() {
        @Override
        public int compare(DocumentSearch.SearchResult o1, DocumentSearch.SearchResult o2) {
            return o1.getSynonym().compareTo(o2.getSynonym());
        }
    };
    for (String inchi : sortedKeys) {
        List<DocumentSearch.SearchResult> res = inchisToResults.get(inchi);
        Collections.sort(res, synonymSorter);
        orderedResults.add(new GroupedInchiResults(inchi, res));
    }

    objectMapper.writerWithView(Object.class).writeValue(outputWriter, orderedResults);
    outputWriter.close();
}

From source file:cli.Main.java

public static void main(String[] args) {
    // Workaround for BKS truststore
    Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1);

    Namespace ns = parseArgs(args);
    if (ns == null) {
        System.exit(1);/*from   w  w w.  j ava  2  s .  c o m*/
    }

    final String username = ns.getString("username");
    final Manager m = new Manager(username);
    if (m.userExists()) {
        try {
            m.load();
        } catch (Exception e) {
            System.err.println("Error loading state file \"" + m.getFileName() + "\": " + e.getMessage());
            System.exit(2);
        }
    }

    switch (ns.getString("command")) {
    case "register":
        if (!m.userHasKeys()) {
            m.createNewIdentity();
        }
        try {
            m.register(ns.getBoolean("voice"));
        } catch (IOException e) {
            System.err.println("Request verify error: " + e.getMessage());
            System.exit(3);
        }
        break;
    case "verify":
        if (!m.userHasKeys()) {
            System.err.println("User has no keys, first call register.");
            System.exit(1);
        }
        if (m.isRegistered()) {
            System.err.println("User registration is already verified");
            System.exit(1);
        }
        try {
            m.verifyAccount(ns.getString("verificationCode"));
        } catch (IOException e) {
            System.err.println("Verify error: " + e.getMessage());
            System.exit(3);
        }
        break;
    case "send":
        if (!m.isRegistered()) {
            System.err.println("User is not registered.");
            System.exit(1);
        }
        String messageText = ns.getString("message");
        if (messageText == null) {
            try {
                messageText = IOUtils.toString(System.in);
            } catch (IOException e) {
                System.err.println("Failed to read message from stdin: " + e.getMessage());
                System.exit(1);
            }
        }

        final List<String> attachments = ns.getList("attachment");
        List<TextSecureAttachment> textSecureAttachments = null;
        if (attachments != null) {
            textSecureAttachments = new ArrayList<>(attachments.size());
            for (String attachment : attachments) {
                try {
                    File attachmentFile = new File(attachment);
                    InputStream attachmentStream = new FileInputStream(attachmentFile);
                    final long attachmentSize = attachmentFile.length();
                    String mime = Files.probeContentType(Paths.get(attachment));
                    textSecureAttachments
                            .add(new TextSecureAttachmentStream(attachmentStream, mime, attachmentSize, null));
                } catch (IOException e) {
                    System.err.println("Failed to add attachment \"" + attachment + "\": " + e.getMessage());
                    System.err.println("Aborting sending.");
                    System.exit(1);
                }
            }
        }

        List<TextSecureAddress> recipients = new ArrayList<>(ns.<String>getList("recipient").size());
        for (String recipient : ns.<String>getList("recipient")) {
            try {
                recipients.add(m.getPushAddress(recipient));
            } catch (InvalidNumberException e) {
                System.err.println("Failed to add recipient \"" + recipient + "\": " + e.getMessage());
                System.err.println("Aborting sending.");
                System.exit(1);
            }
        }
        sendMessage(m, messageText, textSecureAttachments, recipients);
        break;
    case "receive":
        if (!m.isRegistered()) {
            System.err.println("User is not registered.");
            System.exit(1);
        }
        try {
            m.receiveMessages(5, true, new ReceiveMessageHandler(m));
        } catch (IOException e) {
            System.err.println("Error while receiving message: " + e.getMessage());
            System.exit(3);
        } catch (AssertionError e) {
            System.err.println("Failed to receive message (Assertion): " + e.getMessage());
            System.err.println(e.getStackTrace());
            System.err.println(
                    "If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README");
            System.exit(1);
        }
        break;
    }
    m.save();
    System.exit(0);
}

From source file:com.kynetx.ParseRuleset.java

public static void main(String[] args) throws Exception {
    File f = new File(args[0]);
    int notparsed = 0;
    int parsed = 0;

    File[] files = null;/*  ww w.j a va 2  s .c o  m*/
    if (f.isDirectory()) {
        files = f.listFiles();
    } else {
        files = new File[1];
        files[0] = new File(args[0]);
    }
    for (int i = 0; i < files.length; i++) {
        File thefile = files[i];
        long start = System.currentTimeMillis();
        boolean skipfile = false;
        for (int ii = 0; ii < ignore.length; ii++) {
            if (thefile.getCanonicalPath().indexOf(ignore[ii] + ".krl") > 0) {
                skipfile = true;
                break;
            }
        }
        if (thefile.length() == 0 || thefile.length() == 31 || thefile.length() == 162 || skipfile) {
            notparsed = notparsed + 1;
            //               System.out.println("Skipping: " + thefile + " in " + (System.currentTimeMillis() - start) + "ms." );
            //               System.out.println("Skipping " + thefile);
            continue;
        }
        parsed = parsed + 1;
        try {
            ANTLRFileStream input = new ANTLRFileStream(thefile.getCanonicalPath());
            com.kynetx.RuleSetLexer lexer = new com.kynetx.RuleSetLexer(input);
            CommonTokenStream tokens = new CommonTokenStream(lexer);
            com.kynetx.RuleSetParser parser = new com.kynetx.RuleSetParser(tokens);
            parser.ruleset();
            JSONObject js = new JSONObject(parser.rule_json);
            if (parser.parse_errors.size() > 0) {
                for (int ii = 0; ii < parser.parse_errors.size(); ii++) {
                    System.err
                            .println("ERROR FOUND " + parser.parse_errors.get(ii) + " - " + thefile.toString());
                }
            }
            //               System.out.println("Parsed: " + thefile + " in " + (System.currentTimeMillis() - start) + "ms." );
            //System.out.println(unescapeUnicode(js.toString()));
            System.out.println(js.toString());
            //System.out.println("=============");
            //System.out.println(js.toString());
        } catch (Exception e) {
            //               System.out.println("Error: " + thefile + " in " + (System.currentTimeMillis() - start) + "ms." );
            System.out.println("Error " + thefile + " " + e.getMessage());
            e.printStackTrace();
        }
    }
    //         System.out.println("Not Parsed " + notparsed);
    //         System.out.println("Parsed " + parsed);

}

From source file:hd3gtv.tools.Hexview.java

public static void main(String[] args) throws IOException {
    if (args.length == 0) {
        System.err.println("Usage file1.ext file2.ext ...");
        System.exit(1);//from www.ja v  a  2  s .c o  m
    }

    Arrays.asList(args).forEach(f -> {
        try {
            File file = new File(f);

            InputStream in = new BufferedInputStream(new FileInputStream(file), 0xFFFF);

            byte[] buffer = new byte[COLS * ROWS];
            int len;
            Hexview hv = null;

            while ((len = in.read(buffer)) != -1) {
                if (hv == null) {
                    hv = new Hexview(buffer, 0, len);
                    hv.setSize(file.length());
                } else {
                    hv.update(buffer, 0, len);
                }
                System.out.println(hv.getView());
            }

            IOUtils.closeQuietly(in);
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(2);
        }
    });
}

From source file:org.bimserver.build.CreateGitHubRelease.java

public static void main(String[] args) {
    String username = args[0];/*from  ww w .  j  a va  2 s. co  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:cn.vlabs.clb.server.ui.frameservice.image.ImageUtil.java

public static void main(String[] args) throws Exception {
    String srcDirPath = "/Users/clive/test/resize-test/src/";
    String dstDirPath = "/Users/clive/test/resize-test/dst/";
    String[] filenames = { "yilabao.jpg" };
    int[] size = { 600 };
    String[] q = { "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94",
            "95", "96", "97", "98", "99", "100", "101" };

    ImageUtil iu = new ImageUtil();
    for (String fn : filenames) {
        for (int i = 0; i < size.length; i++) {
            for (int j = 0; j < q.length; j++) {
                iu.quality = q[j];//from w  w w  .  j a  v  a2 s  . co m
                String filename = iu.getTempfilename(fn, size[i], q[j]);
                InputStream fis = new FileInputStream(new File(srcDirPath + fn));
                byte[] cache = inputStreamToByte(fis);
                long start = System.currentTimeMillis();
                InputStream ins = byteToInputStream(cache);
                File f = new File(dstDirPath + filename);
                OutputStream fos = new FileOutputStream(f);
                iu.resize(ins, fos, size[i], "width");
                long end = System.currentTimeMillis();
                System.out.printf("filename=%-40s time=%-10d size=%-10d scale-width=%-10d quality=%s\n", fn,
                        (end - start), f.length(), size[i], q[j]);
            }
        }
    }

}