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:org.eclipse.swt.snippets.SnippetLauncher.java

public static void main(String[] args) {
    File sourceDir = SnippetsConfig.SNIPPETS_SOURCE_DIR;
    boolean hasSource = sourceDir.exists();
    int count = 500;
    if (hasSource) {
        File[] files = sourceDir.listFiles();
        if (files.length > 0)
            count = files.length;/*ww  w  . ja v a2  s. c om*/
    }
    for (int i = 1; i < count; i++) {
        if (SnippetsConfig.isPrintingSnippet(i))
            continue; // avoid printing to printer
        String className = "Snippet" + i;
        Class<?> clazz = null;
        try {
            clazz = Class.forName(SnippetsConfig.SNIPPETS_PACKAGE + "." + className);
        } catch (ClassNotFoundException e) {
        }
        if (clazz != null) {
            System.out.println("\n" + clazz.getName());
            if (hasSource) {
                File sourceFile = new File(sourceDir, className + ".java");
                try (FileReader reader = new FileReader(sourceFile);) {
                    char[] buffer = new char[(int) sourceFile.length()];
                    reader.read(buffer);
                    String source = String.valueOf(buffer);
                    int start = source.indexOf("package");
                    start = source.indexOf("/*", start);
                    int end = source.indexOf("* For a list of all");
                    System.out.println(source.substring(start, end - 3));
                    boolean skip = false;
                    String platform = SWT.getPlatform();
                    if (source.contains("PocketPC")) {
                        platform = "PocketPC";
                        skip = true;
                    } else if (source.contains("OpenGL")) {
                        platform = "OpenGL";
                        skip = true;
                    } else if (source.contains("JavaXPCOM")) {
                        platform = "JavaXPCOM";
                        skip = true;
                    } else {
                        String[] platforms = { "win32", "gtk" };
                        for (int p = 0; p < platforms.length; p++) {
                            if (!platforms[p].equals(platform) && source.contains("." + platforms[p])) {
                                platform = platforms[p];
                                skip = true;
                                break;
                            }
                        }
                    }
                    if (skip) {
                        System.out.println("...skipping " + platform + " example...");
                        continue;
                    }
                } catch (Exception e) {
                }
            }
            Method method = null;
            String[] param = SnippetsConfig.getSnippetArguments(i);
            try {
                method = clazz.getMethod("main", param.getClass());
            } catch (NoSuchMethodException e) {
                System.out.println("   Did not find main(String [])");
            }
            if (method != null) {
                try {
                    method.invoke(clazz, new Object[] { param });
                } catch (IllegalAccessException e) {
                    System.out.println("   Failed to launch (illegal access)");
                } catch (IllegalArgumentException e) {
                    System.out.println("   Failed to launch (illegal argument to main)");
                } catch (InvocationTargetException e) {
                    System.out.println("   Exception in Snippet: " + e.getTargetException());
                }
            }
        }
    }
}

From source file:InsertTextFileToOracle.java

public static void main(String[] args) throws Exception {
    String id = "001";
    String fileName = "fileName.txt";

    FileInputStream fis = null;/*from   w ww .j  av a  2s . co m*/
    PreparedStatement pstmt = null;
    Connection conn = null;
    try {
        conn = getConnection();
        conn.setAutoCommit(false);
        File file = new File(fileName);
        fis = new FileInputStream(file);
        pstmt = conn.prepareStatement("insert into DataFiles(id, fileName, fileBody) values (?, ?, ?)");
        pstmt.setString(1, id);
        pstmt.setString(2, fileName);
        pstmt.setAsciiStream(3, fis, (int) file.length());
        pstmt.executeUpdate();
        conn.commit();
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        pstmt.close();
        fis.close();
        conn.close();
    }
}

From source file:net.minecraftforge.fml.repackage.com.nothome.delta.GDiffPatcher.java

/**
 * Simple command line tool to patch a file.
 *//*from   w ww . j  ava  2s . c o  m*/
public static void main(String argv[]) {

    if (argv.length != 3) {
        System.err.println("usage GDiffPatch source patch output");
        System.err.println("aborting..");
        return;
    }
    try {
        File sourceFile = new File(argv[0]);
        File patchFile = new File(argv[1]);
        File outputFile = new File(argv[2]);

        if (sourceFile.length() > Integer.MAX_VALUE || patchFile.length() > Integer.MAX_VALUE) {
            System.err.println("source or patch is too large, max length is " + Integer.MAX_VALUE);
            System.err.println("aborting..");
            return;
        }
        GDiffPatcher patcher = new GDiffPatcher();
        patcher.patch(sourceFile, patchFile, outputFile);

        System.out.println("finished patching file");

    } catch (Exception ioe) { //gls031504a
        System.err.println("error while patching: " + ioe);
    }
}

From source file:com.basistech.rosette.dm.json.array.CompareJsons.java

public static void main(String[] args) throws Exception {
    File plenty = new File(args[0]);
    System.out.println(String.format("Original file length %d", plenty.length()));
    ObjectMapper inputMapper = AnnotatedDataModelModule.setupObjectMapper(new ObjectMapper());
    AnnotatedText[] texts = inputMapper.readValue(plenty, AnnotatedText[].class);
    System.out.println(String.format("%d documents", texts.length));
    runWithFormat(texts, new FactoryFactory() {
        @Override/*from w ww . j a  v a 2s.  co m*/
        public JsonFactory newFactory() {
            return new JsonFactory();
        }
    }, "Plain");
    runWithFormat(texts, new FactoryFactory() {
        @Override
        public JsonFactory newFactory() {
            return new SmileFactory();
        }
    }, "SMILE");

    runWithFormat(texts, new FactoryFactory() {
        @Override
        public JsonFactory newFactory() {
            return new CBORFactory();
        }
    }, "CBOR");
}

From source file:com.addthis.hydra.data.MakeBloom.java

public static void main(String[] args) throws java.io.IOException, com.addthis.maljson.JSONException {
    if (args.length != 1 && args.length != 2) {
        throw new IllegalArgumentException("usage: MakeBloom word-list-file [bloom-file]");
    }//from   ww  w  . ja v  a2 s.c o m

    File in = new File(args[0]);
    String[] words = getWords(in);

    BloomFilter bf = new BloomFilter(words.length, fp_rate);
    log.debug("Created: BloomFilter(" + bf.buckets() + " buckets, " + bf.getHashCount() + " hashes); FP rate = "
            + fp_rate);
    for (int i = 0; i < words.length; i++) {
        bf.add(words[i]);
    }
    log.debug("Added words");

    File out = args.length == 2 ? new File(args[1])
            : LessFiles.replaceSuffix(in, "-" + words.length + "-" + fpRate + ".bloom");
    log.debug("Writing [" + out + "]");
    LessFiles.write(out, org.apache.commons.codec.binary.Base64.encodeBase64(BloomFilter.serialize(bf)), false);
    log.debug("Wrote " + out.length() + " bytes to [" + out + "]");
}

From source file:importer.handler.post.stages.SAXSplitter.java

public static void main(String[] args) {
    if (args.length == 1) {
        File f = new File(args[0]);
        byte[] data = new byte[(int) f.length()];
        try {//ww w. j  a  v  a2  s . c  o  m
            FileInputStream fis = new FileInputStream(f);
            fis.read(data);
            SAXSplitter ss = new SAXSplitter();
            JSONArray jArr = ss.scan(new String(data, "UTF-8"));
            String jStr = jArr.toJSONString();
            System.out.println(jStr.replaceAll("\\\\/", "/"));
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

From source file:com.sight.facialrecog.util.ImageManipulation.java

/**
 * @param args//from w  w  w.  j  av a 2 s .  co  m
 */
public static void main(String[] args) {
    File file = new File("/home/sight/Pictures/imagetest/close.jpg");

    try {
        /*
         * Reading an Image file from file system
         */
        FileInputStream imageInFile = new FileInputStream(file);
        byte imageData[] = new byte[(int) file.length()];
        imageInFile.read(imageData);

        /*
         * Converting Image byte array into Base64 String
         */
        String imageDataString = encodeImage(imageData);
        System.out.println(imageDataString);

        /*
         * Converting a Base64 String into Image byte array
         */
        byte[] imageByteArray = decodeImage(imageDataString);

        /*
         * Write an image byte array into file system
         */
        FileOutputStream imageOutFile = new FileOutputStream(
                "/home/sight/Pictures/imagetest/close-after-convert.jpg");
        imageOutFile.write(imageByteArray);

        imageInFile.close();
        imageOutFile.close();

        System.out.println("Image Successfully Manipulated!");
    } catch (FileNotFoundException e) {
        System.out.println("Image not found" + e);
    } catch (IOException ioe) {
        System.out.println("Exception while reading the Image " + ioe);
    }

}

From source file:createSod.java

/**
 * @param args//from  w w  w.java 2  s.  co  m
 * @throws CMSException 
 */
public static void main(String[] args) throws Exception {

    try {
        CommandLine options = verifyArgs(args);
        String privateKeyLocation = options.getOptionValue("privatekey");
        String keyPassword = options.getOptionValue("keypass");
        String certificate = options.getOptionValue("certificate");
        String sodContent = options.getOptionValue("content");
        String sod = "";
        if (options.hasOption("out")) {
            sod = options.getOptionValue("out");
        }

        // CHARGEMENT DU FICHIER PKCS#12

        KeyStore ks = null;
        char[] password = null;

        Security.addProvider(new BouncyCastleProvider());
        try {
            ks = KeyStore.getInstance("PKCS12");
            // Password pour le fichier personnal_nyal.p12
            password = keyPassword.toCharArray();
            ks.load(new FileInputStream(privateKeyLocation), password);
        } catch (Exception e) {
            System.out.println("Erreur: fichier " + privateKeyLocation
                    + " n'est pas un fichier pkcs#12 valide ou passphrase incorrect");
            return;
        }

        // RECUPERATION DU COUPLE CLE PRIVEE/PUBLIQUE ET DU CERTIFICAT PUBLIQUE

        X509Certificate cert = null;
        PrivateKey privatekey = null;
        PublicKey publickey = null;

        try {
            Enumeration en = ks.aliases();
            String ALIAS = "";
            Vector vectaliases = new Vector();

            while (en.hasMoreElements())
                vectaliases.add(en.nextElement());
            String[] aliases = (String[]) (vectaliases.toArray(new String[0]));
            for (int i = 0; i < aliases.length; i++)
                if (ks.isKeyEntry(aliases[i])) {
                    ALIAS = aliases[i];
                    break;
                }
            privatekey = (PrivateKey) ks.getKey(ALIAS, password);
            cert = (X509Certificate) ks.getCertificate(ALIAS);
            publickey = ks.getCertificate(ALIAS).getPublicKey();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        // Chargement du certificat  partir du fichier

        InputStream inStream = new FileInputStream(certificate);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        cert = (X509Certificate) cf.generateCertificate(inStream);
        inStream.close();

        // Chargement du fichier qui va tre sign

        File file_to_sign = new File(sodContent);
        byte[] buffer = new byte[(int) file_to_sign.length()];
        DataInputStream in = new DataInputStream(new FileInputStream(file_to_sign));
        in.readFully(buffer);
        in.close();

        // Chargement des certificats qui seront stocks dans le fichier .p7
        // Ici, seulement le certificat personnal_nyal.cer sera associ.
        // Par contre, la chane des certificats non.

        ArrayList certList = new ArrayList();
        certList.add(cert);
        CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList),
                "BC");

        CMSSignedDataGenerator signGen = new CMSSignedDataGenerator();

        // privatekey correspond  notre cl prive rcupre du fichier PKCS#12
        // cert correspond au certificat publique personnal_nyal.cer
        // Le dernier argument est l'algorithme de hachage qui sera utilis

        signGen.addSigner(privatekey, cert, CMSSignedDataGenerator.DIGEST_SHA1);
        signGen.addCertificatesAndCRLs(certs);
        CMSProcessable content = new CMSProcessableByteArray(buffer);

        // Generation du fichier CMS/PKCS#7
        // L'argument deux permet de signifier si le document doit tre attach avec la signature
        //     Valeur true:  le fichier est attach (c'est le cas ici)
        //     Valeur false: le fichier est dtach

        CMSSignedData signedData = signGen.generate(content, true, "BC");
        byte[] signeddata = signedData.getEncoded();

        // Ecriture du buffer dans un fichier.   

        if (sod.equals("")) {
            System.out.print(signeddata.toString());
        } else {
            FileOutputStream envfos = new FileOutputStream(sod);
            envfos.write(signeddata);
            envfos.close();
        }

    } catch (OptionException oe) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(NAME, getOptions());
        System.exit(-1);
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }

}

From source file:importer.handler.post.stages.Splitter.java

/** test and commandline utility */
public static void main(String[] args) {
    if (args.length >= 1) {
        try {//w  w w  . j  ava 2s  .co  m
            int i = 0;
            int fileIndex = 0;
            // see if the user supplied a conf file
            String textConf = Discriminator.defaultConf;
            while (i < args.length) {
                if (args[i].equals("-c") && i < args.length - 1) {
                    textConf = readConfig(args[i + 1]);
                    i += 2;
                } else {
                    fileIndex = i;
                    i++;
                }
            }
            File f = new File(args[fileIndex]);
            char[] data = new char[(int) f.length()];
            FileReader fr = new FileReader(f);
            fr.read(data);
            JSONObject config = (JSONObject) JSONValue.parse(textConf);
            Splitter split = new Splitter(config);
            Map<String, String> map = split.split(new String(data));
            Set<String> keys = map.keySet();
            String rawFileName = args[fileIndex];
            int pos = rawFileName.lastIndexOf(".");
            if (pos != -1)
                rawFileName = rawFileName.substring(0, pos);
            Iterator<String> iter = keys.iterator();
            while (iter.hasNext()) {
                String key = iter.next();
                String fName = rawFileName + "-" + key + ".xml";
                File g = new File(fName);
                if (g.exists())
                    g.delete();
                FileOutputStream fos = new FileOutputStream(g);
                fos.write(map.get(key).getBytes("UTF-8"));
                fos.close();
            }
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
    } else
        System.out.println("usage: java -jar split.jar [-c json-config] <tei-xml>\n");
}

From source file:acmi.l2.clientmod.l2_version_switcher.Main.java

public static void main(String[] args) {
    if (args.length != 3 && args.length != 4) {
        System.out.println("USAGE: l2_version_switcher.jar host game version <--splash> <filter>");
        System.out.println("EXAMPLE: l2_version_switcher.jar " + L2.NCWEST_HOST + " " + L2.NCWEST_GAME
                + " 1 \"system\\*\"");
        System.out.println(/*from   www .  ja  va2s.  c  o  m*/
                "         l2_version_switcher.jar " + L2.PLAYNC_TEST_HOST + " " + L2.PLAYNC_TEST_GAME + " 48");
        System.exit(0);
    }

    List<String> argsList = new ArrayList<>(Arrays.asList(args));
    String host = argsList.get(0);
    String game = argsList.get(1);
    int version = Integer.parseInt(argsList.get(2));
    Helper helper = new Helper(host, game, version);
    boolean available = false;

    try {
        available = helper.isAvailable();
    } catch (IOException e) {
        System.err.print(e.getClass().getSimpleName());
        if (e.getMessage() != null) {
            System.err.print(": " + e.getMessage());
        }

        System.err.println();
    }

    System.out.println(String.format("Version %d available: %b", version, available));
    if (!available) {
        System.exit(0);
    }

    List<FileInfo> fileInfoList = null;
    try {
        fileInfoList = helper.getFileInfoList();
    } catch (IOException e) {
        System.err.println("Couldn\'t get file info map");
        System.exit(1);
    }

    boolean splash = argsList.remove("--splash");
    if (splash) {
        Optional<FileInfo> splashObj = fileInfoList.stream()
                .filter(fi -> fi.getPath().contains("sp_32b_01.bmp")).findAny();
        if (splashObj.isPresent()) {
            try (InputStream is = new FilterInputStream(
                    Util.getUnzipStream(helper.getDownloadStream(splashObj.get().getPath()))) {
                @Override
                public int read() throws IOException {
                    int b = super.read();
                    if (b >= 0)
                        b ^= 0x36;
                    return b;
                }

                @Override
                public int read(byte[] b, int off, int len) throws IOException {
                    int r = super.read(b, off, len);
                    if (r >= 0) {
                        for (int i = 0; i < r; i++)
                            b[off + i] ^= 0x36;
                    }
                    return r;
                }
            }) {
                new DataInputStream(is).readFully(new byte[28]);
                BufferedImage bi = ImageIO.read(is);

                JFrame frame = new JFrame("Lineage 2 [" + version + "] " + splashObj.get().getPath());
                frame.setContentPane(new JComponent() {
                    {
                        setPreferredSize(new Dimension(bi.getWidth(), bi.getHeight()));
                    }

                    @Override
                    protected void paintComponent(Graphics g) {
                        g.drawImage(bi, 0, 0, null);
                    }
                });
                frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("Splash not found");
        }
        return;
    }

    String filter = argsList.size() > 3 ? separatorsToSystem(argsList.get(3)) : null;

    File l2Folder = new File(System.getProperty("user.dir"));
    List<FileInfo> toUpdate = fileInfoList.parallelStream().filter(fi -> {
        String filePath = separatorsToSystem(fi.getPath());

        if (filter != null && !wildcardMatch(filePath, filter, IOCase.INSENSITIVE))
            return false;
        File file = new File(l2Folder, filePath);

        try {
            if (file.exists() && file.length() == fi.getSize() && Util.hashEquals(file, fi.getHash())) {
                System.out.println(filePath + ": OK");
                return false;
            }
        } catch (IOException e) {
            System.out.println(filePath + ": couldn't check hash: " + e);
            return true;
        }

        System.out.println(filePath + ": need update");
        return true;
    }).collect(Collectors.toList());

    List<String> errors = Collections.synchronizedList(new ArrayList<>());
    ExecutorService executor = Executors.newFixedThreadPool(16);
    CompletableFuture[] tasks = toUpdate.stream().map(fi -> CompletableFuture.runAsync(() -> {
        String filePath = separatorsToSystem(fi.getPath());
        File file = new File(l2Folder, filePath);

        File folder = file.getParentFile();
        if (!folder.exists()) {
            if (!folder.mkdirs()) {
                errors.add(filePath + ": couldn't create parent dir");
                return;
            }
        }

        try (InputStream input = Util
                .getUnzipStream(new BufferedInputStream(helper.getDownloadStream(fi.getPath())));
                OutputStream output = new BufferedOutputStream(new FileOutputStream(file))) {
            byte[] buffer = new byte[Math.min(fi.getSize(), 1 << 24)];
            int pos = 0;
            int r;
            while ((r = input.read(buffer, pos, buffer.length - pos)) >= 0) {
                pos += r;
                if (pos == buffer.length) {
                    output.write(buffer, 0, pos);
                    pos = 0;
                }
            }
            if (pos != 0) {
                output.write(buffer, 0, pos);
            }
            System.out.println(filePath + ": OK");
        } catch (IOException e) {
            String msg = filePath + ": FAIL: " + e.getClass().getSimpleName();
            if (e.getMessage() != null) {
                msg += ": " + e.getMessage();
            }
            errors.add(msg);
        }
    }, executor)).toArray(CompletableFuture[]::new);
    CompletableFuture.allOf(tasks).thenRun(() -> {
        for (String err : errors)
            System.err.println(err);
        executor.shutdown();
    });
}