Example usage for org.apache.commons.io FileUtils readFileToString

List of usage examples for org.apache.commons.io FileUtils readFileToString

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils readFileToString.

Prototype

public static String readFileToString(File file) throws IOException 

Source Link

Document

Reads the contents of a file into a String using the default encoding for the VM.

Usage

From source file:com.moscona.dataSpace.debug.BadLocks.java

public static void main(String[] args) {
    try {/*w w w.ja  va 2 s .c o m*/
        String lockFile = "C:\\Users\\Admin\\projects\\intellitrade\\tmp\\bad.lock";
        FileUtils.touch(new File(lockFile));
        FileOutputStream stream = new FileOutputStream(lockFile);
        //            FileInputStream stream = new FileInputStream(lockFile);
        FileChannel channel = stream.getChannel();
        //            FileLock lock = channel.lock(0,Long.MAX_VALUE, true);
        FileLock lock = channel.lock();
        stream.write(new UndocumentedJava().pid().getBytes());
        stream.flush();
        long start = System.currentTimeMillis();
        //            while (System.currentTimeMillis()-start < 10000) {
        //                Thread.sleep(500);
        //            }
        lock.release();
        stream.close();
        File f = new File(lockFile);
        System.out.println("Before write: " + FileUtils.readFileToString(f));
        FileUtils.writeStringToFile(f, "written after lock released");
        System.out.println("After write: " + FileUtils.readFileToString(f));
    } catch (Exception e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }

}

From source file:com.atlauncher.Bootstrap.java

public static void main(String[] args) {
    String json = null;//  www.  j  ava 2 s  . c  om

    if (!Files.isDirectory(PATH)) {
        try {
            Files.createDirectories(PATH);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    try {
        json = IOUtils.toString(URI.create("http://download.nodecdn.net/containers/atl/v4/app.json"));
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }

    Application application = GSON.fromJson(json, Application.class);

    Dependency currentDependency = null;

    if (Files.exists(PATH.resolve("nwjs.json"))) {
        try {
            currentDependency = GSON.fromJson(FileUtils.readFileToString(PATH.resolve("nwjs.json").toFile()),
                    Dependency.class);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    for (Dependency dependency : application.getDependencies()) {
        if (dependency.shouldInstall() && !dependency.matches(currentDependency)) {
            if (Files.isDirectory(PATH.resolve("nwjs/"))) {
                try {
                    FileUtils.deleteDirectory(PATH.resolve("nwjs/").toFile());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            try {
                File zipFile = PATH.resolve("nwjs/temp.zip").toFile();
                FileUtils.copyURLToFile(dependency.getUrl(), zipFile);
                Utils.unzip(zipFile, PATH.resolve("nwjs/").toFile());
                FileUtils.forceDelete(zipFile);

                currentDependency = dependency;

                FileUtils.writeStringToFile(PATH.resolve("nwjs.json").toFile(), GSON.toJson(dependency));

                break;
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(1);
            }
        }
    }

    App currentApp = null;

    if (Files.exists(PATH.resolve("app.json"))) {
        try {
            currentApp = GSON.fromJson(FileUtils.readFileToString(PATH.resolve("app.json").toFile()),
                    App.class);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    if (!application.getApp().matches(currentApp)
            || (currentApp != null && !Files.exists(PATH.resolve(currentApp.getFilename())))) {
        if (currentApp != null && Files.exists(PATH.resolve(currentApp.getFilename()))) {
            try {
                FileUtils.forceDelete(PATH.resolve(currentApp.getFilename()).toFile());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            FileUtils.copyURLToFile(application.getApp().getUrl(),
                    PATH.resolve(application.getApp().getFilename()).toFile());

            currentApp = application.getApp();

            FileUtils.writeStringToFile(PATH.resolve("app.json").toFile(), GSON.toJson(application.getApp()));
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    if (currentDependency == null || currentApp == null) {
        System.exit(1);
    }

    List<String> arguments = new ArrayList<>();
    arguments.add(PATH.resolve("nwjs/").toAbsolutePath() + currentDependency.getStartup());
    arguments.add(currentApp.getFilename());
    ProcessBuilder processBuilder = new ProcessBuilder(arguments);
    processBuilder.directory(PATH.toFile());
    try {
        processBuilder.start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:edu.illinois.cs.cogcomp.nlp.tokenizer.HashCollisionReport.java

/**
 * Read each test file in the directory, tokenize and create the token view. Then check for
 * collisions./*from   w w  w . ja  va  2s.com*/
 * @param args
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    if (args.length == 0)
        error("Must pass in the name of a directory with files to test against.");
    File dir = new File(args[0]);
    if (!dir.exists()) {
        error("The directory did not exist : " + dir);
    }
    if (!dir.isDirectory()) {
        error("The path was not a directory : " + dir);
    }
    File[] files = dir.listFiles();
    for (File file : files) {
        if (file.isFile()) {
            String normal = FileUtils.readFileToString(file);
            TextAnnotationBuilder tabldr = new TokenizerTextAnnotationBuilder(new StatefulTokenizer());
            TextAnnotation taNormal = tabldr.createTextAnnotation("test", "normal", normal);
            List<Constituent> normalToks = taNormal.getView(ViewNames.TOKENS).getConstituents();
            HashMap<Integer, Constituent> hashmap = new HashMap<>();

            // add each constituent to the map keyed by it's hashcode. Check first to see if the hashcode
            // is already used, if it is report it.
            for (Constituent c : normalToks) {
                int code = c.hashCode();
                if (hashmap.containsKey(code)) {
                    Constituent dup = hashmap.get(code);
                    System.err.println(c + " == " + dup);
                } else {
                    hashmap.put(code, c);
                }
            }
        }
    }

}

From source file:com.axiomine.largecollections.generator.GeneratorWritableSet.java

public static void main(String[] args) throws Exception {
    //Package of the new class you are generating Ex. com.mypackage
    String MY_PACKAGE = args[0];/* w w w .  java 2s .c om*/
    //Any custom imports you need (: seperated). Use - if no custom imports are included
    //Ex. java.util.*:java.lang.Random     
    String CUSTOM_IMPORTS = args[1].equals("-") ? "" : args[1];
    //Package of your Key serializer class. Use com.axiomine.bigcollections.functions
    String T = args[2];

    String tCls = T;

    if (tCls.equals("byte[]")) {
        tCls = "BytesArray";
    }
    String CLASS_NAME = tCls + "Set";
    File root = new File("");
    File outFile = new File(root.getAbsolutePath() + "/src/main/java/" + MY_PACKAGE.replaceAll("\\.", "/") + "/"
            + CLASS_NAME + ".java");

    if (outFile.exists()) {
        System.out.println(outFile.getAbsolutePath() + " already exists. Please delete it and try again");
    }
    {
        String[] imports = null;
        String importStr = "";

        if (!StringUtils.isBlank(CUSTOM_IMPORTS)) {
            CUSTOM_IMPORTS.split(":");
            for (String s : imports) {
                importStr = "import " + s + ";\n";
            }
        }

        String program = FileUtils.readFileToString(
                new File(root.getAbsolutePath() + "/src/main/resources/WritableSetTemplate.java"));

        program = program.replaceAll("#MY_PACKAGE#", MY_PACKAGE);
        program = program.replaceAll("#CUSTOM_IMPORTS#", importStr);

        program = program.replaceAll("#CLASS_NAME#", CLASS_NAME);
        program = program.replaceAll("#T#", T);
        program = program.replaceAll("#TCLS#", tCls);

        System.out.println(outFile.getAbsolutePath());
        FileUtils.writeStringToFile(outFile, program);
    }
}

From source file:com.axiomine.largecollections.generator.GeneratorPrimitiveSet.java

public static void main(String[] args) throws Exception {
    //Package of the new class you are generating Ex. com.mypackage
    String MY_PACKAGE = args[0];/*from w  w  w.ja  v a 2  s. co  m*/
    //Any custom imports you need (: seperated). Use - if no custom imports are included
    //Ex. java.util.*:java.lang.Random     
    String CUSTOM_IMPORTS = args[1].equals("-") ? "" : args[1];
    //Package of your Key serializer class. Use com.axiomine.bigcollections.functions
    String T = args[2];

    String tCls = T;

    if (tCls.equals("byte[]")) {
        tCls = "BytesArray";
    }
    String CLASS_NAME = tCls + "Set";
    File root = new File("");
    File outFile = new File(root.getAbsolutePath() + "/src/main/java/" + MY_PACKAGE.replaceAll("\\.", "/") + "/"
            + CLASS_NAME + ".java");

    if (outFile.exists()) {
        System.out.println(outFile.getAbsolutePath() + " already exists. Please delete it and try again");
    }
    {
        String[] imports = null;
        String importStr = "";

        if (!StringUtils.isBlank(CUSTOM_IMPORTS)) {
            CUSTOM_IMPORTS.split(":");
            for (String s : imports) {
                importStr = "import " + s + ";\n";
            }
        }

        String program = FileUtils.readFileToString(
                new File(root.getAbsolutePath() + "/src/main/resources/PrimitiveSetTemplate.java"));

        program = program.replaceAll("#MY_PACKAGE#", MY_PACKAGE);
        program = program.replaceAll("#CUSTOM_IMPORTS#", importStr);

        program = program.replaceAll("#CLASS_NAME#", CLASS_NAME);
        program = program.replaceAll("#T#", T);
        program = program.replaceAll("#TCLS#", tCls);

        System.out.println(outFile.getAbsolutePath());
        FileUtils.writeStringToFile(outFile, program);
    }
}

From source file:com.axiomine.largecollections.generator.GeneratorWritableList.java

public static void main(String[] args) throws Exception {
    //Package of the new class you are generating Ex. com.mypackage
    String MY_PACKAGE = args[0];/*from   w w  w. jav a2 s  . co  m*/
    //Any custom imports you need (: seperated). Use - if no custom imports are included
    //Ex. java.util.*:java.lang.Random     
    String CUSTOM_IMPORTS = args[1].equals("-") ? "" : args[1];
    //Package of your Key serializer class. Use com.axiomine.bigcollections.functions
    String T = args[2];

    String tCls = T;

    if (tCls.equals("byte[]")) {
        tCls = "BytesArray";
    }
    String CLASS_NAME = tCls + "List";
    File root = new File("");
    File outFile = new File(root.getAbsolutePath() + "/src/main/java/" + MY_PACKAGE.replaceAll("\\.", "/") + "/"
            + CLASS_NAME + ".java");

    if (outFile.exists()) {
        System.out.println(outFile.getAbsolutePath() + " already exists. Please delete it and try again");
    }
    {
        String[] imports = null;
        String importStr = "";

        if (!StringUtils.isBlank(CUSTOM_IMPORTS)) {
            CUSTOM_IMPORTS.split(":");
            for (String s : imports) {
                importStr = "import " + s + ";\n";
            }
        }

        String program = FileUtils.readFileToString(
                new File(root.getAbsolutePath() + "/src/main/resources/WritableListTemplate.java"));

        program = program.replaceAll("#MY_PACKAGE#", MY_PACKAGE);
        program = program.replaceAll("#CUSTOM_IMPORTS#", importStr);

        program = program.replaceAll("#CLASS_NAME#", CLASS_NAME);
        program = program.replaceAll("#T#", T);
        program = program.replaceAll("#TCLS#", tCls);

        System.out.println(outFile.getAbsolutePath());
        FileUtils.writeStringToFile(outFile, program);
    }
}

From source file:com.axiomine.largecollections.generator.GeneratorPrimitiveList.java

public static void main(String[] args) throws Exception {
    //Package of the new class you are generating Ex. com.mypackage
    String MY_PACKAGE = args[0];/*ww  w  .j a v a 2s  .  c  om*/
    //Any custom imports you need (: seperated). Use - if no custom imports are included
    //Ex. java.util.*:java.lang.Random     
    String CUSTOM_IMPORTS = args[1].equals("-") ? "" : args[1];
    //Package of your Key serializer class. Use com.axiomine.bigcollections.functions
    String T = args[2];

    String tCls = T;

    if (tCls.equals("byte[]")) {
        tCls = "BytesArray";
    }
    String CLASS_NAME = tCls + "List";
    File root = new File("");
    File outFile = new File(root.getAbsolutePath() + "/src/main/java/" + MY_PACKAGE.replaceAll("\\.", "/") + "/"
            + CLASS_NAME + ".java");

    if (outFile.exists()) {
        System.out.println(outFile.getAbsolutePath() + " already exists. Please delete it and try again");
    }
    {
        String[] imports = null;
        String importStr = "";

        if (!StringUtils.isBlank(CUSTOM_IMPORTS)) {
            CUSTOM_IMPORTS.split(":");
            for (String s : imports) {
                importStr = "import " + s + ";\n";
            }
        }

        String program = FileUtils.readFileToString(
                new File(root.getAbsolutePath() + "/src/main/resources/PrimitiveListTemplate.java"));

        program = program.replaceAll("#MY_PACKAGE#", MY_PACKAGE);
        program = program.replaceAll("#CUSTOM_IMPORTS#", importStr);

        program = program.replaceAll("#CLASS_NAME#", CLASS_NAME);
        program = program.replaceAll("#T#", T);
        program = program.replaceAll("#TCLS#", tCls);

        System.out.println(outFile.getAbsolutePath());
        FileUtils.writeStringToFile(outFile, program);
    }
}

From source file:PodbaseMetadataMigration2.java

public static void main(String[] args) throws Exception {
    System.out.println("Running data migration");

    String projectString = FileUtils.readFileToString(new File("projects.txt"));
    Map<String, Integer> projectIdMapping = new HashMap<String, Integer>();
    for (String line : projectString.split("\n")) {
        String[] split = line.split(":");
        int id = Integer.parseInt(split[0].trim());
        String name = split[1].trim();
        projectIdMapping.put(name, id);//from w  w w  .  ja  va2s  .  c  om
    }

    System.out.println("Reading projects..");
    List<ProjectEntry> projects = dataFromFile("./migrate/projects.data", ProjectEntry.class);
    projectIdMap = parseProjectMap(projects, projectIdMapping);

    System.out.println("Found " + projects.size() + " projects.");

    System.out.println("Reading tags..");
    List<TagEntry> tags = dataFromFile("./migrate/tags.data", TagEntry.class);
    System.out.println("Found " + tags.size() + " tags.");

    System.out.println("Reading templates..");
    List<TemplateEntry> templates = dataFromFile("./migrate/templates.data", TemplateEntry.class);
    System.out.println("Found " + templates.size() + " templates.");

    System.out.println("Reading template fields..");
    List<TemplateFieldEntry> templateFields = dataFromFile("./migrate/template_fields.data",
            TemplateFieldEntry.class);
    System.out.println("Found " + templateFields.size() + " templateFields.");

    int entryCount = tags.size() + templates.size() + templateFields.size();

    //System.out.println("Generating Project SQL");
    //String projectSql = generateSql((List<AbstractEntry>)(List<?>)projects);
    System.out.println("Generating Attribute SQL");
    String imageAttributes = generateSql((List<AbstractEntry>) (List<?>) tags);
    System.out.println("Generating Image SQL");
    String databaseImages = generateDatabaseImageSql();
    //System.out.println("Generating Directory SQL");
    //String directorySql = generateDirectorySql(projects);

    //System.out.println("Generating Template SQL");
    //String templateSql = generateSql((List<AbstractEntry>)(List<?>)templates);
    //System.out.println("Generating Field SQL");
    //String fieldsSql = generateSql((List<AbstractEntry>)(List<?>)templateFields);

    System.out.println("Writing database.sql");
    BufferedWriter bw = new BufferedWriter(new FileWriter(new File("./database.sql")));
    //bw.append(projectSql);
    //bw.append("\n\n");
    bw.append(databaseImages);
    bw.append("\n\n");
    //bw.append(directorySql);
    //bw.append("\n\n");
    bw.append(imageAttributes);
    bw.append("\n\n");
    //      bw.append(templateSql);
    //      bw.append("\n\n");
    //      bw.append(fieldsSql);
    //      bw.append("\n\n");
    bw.close();

    System.out.println("Writing missingImages.txt");
    bw = new BufferedWriter(new FileWriter(new File("./missingImages.txt")));
    for (String img : missingImages) {
        bw.append(img + "\n");
    }
    bw.close();

    System.out.println("Migration completed successfully!");
}

From source file:craterdog.security.DigitalNotaryMain.java

public static void main(String[] args) throws ParseException, IOException {
    HelpFormatter help = new HelpFormatter();
    Options options = new Options();
    options.addOption("help", false, "print this message");
    options.addOption("pubfile", true, "public key input file");
    options.addOption("prvfile", true, "private key input file");

    try {/*  ww w  .  j  a  va  2  s  .  c  o  m*/
        CommandLine cli = new BasicParser().parse(options, args);
        String pubfile = cli.getOptionValue("pubfile");
        String prvfile = cli.getOptionValue("prvfile");

        NotaryKey notaryKey = notarization.generateNotaryKey();

        if (pubfile != null || prvfile != null) {
            if (pubfile == null)
                throw new MissingArgumentException("Missing option: pubfile");
            if (prvfile == null)
                throw new MissingArgumentException("Missing option: prvfile");

            CertificateManager manager = new RsaCertificateManager();
            PublicKey publicKey = manager.decodePublicKey(FileUtils.readFileToString(new File(pubfile)));
            char[] password = System.console().readPassword("input private key password: ");
            PrivateKey privateKey = manager.decodePrivateKey(FileUtils.readFileToString(new File(prvfile)),
                    password);

            notaryKey.signingKey = privateKey;
            notaryKey.verificationKey = publicKey;

            // make sure it works
            DigitalSeal seal = notarization.notarizeDocument("test document", "test document", notaryKey);
            notarization.documentIsValid("test document", seal, publicKey);
        }
        char[] password = System.console().readPassword("verficationKey password: ");
        System.out.println(notarization.serializeNotaryKey(notaryKey, password));
    } catch (MissingArgumentException | FileNotFoundException ex) {
        System.out.println(ex.getMessage());
        help.printHelp(CMD_LINE_SYNTAX, options);
        System.exit(1);
    }
}

From source file:com.axiomine.largecollections.generator.GeneratorPrimitivePrimitive.java

public static void main(String[] args) throws Exception {
    //Package of the new class you are generating Ex. com.mypackage
    String MY_PACKAGE = args[0];/*from   w ww .ja  va 2 s .  c  o  m*/
    //Any custom imports you need (: seperated). Use - if no custom imports are included
    //Ex. java.util.*:java.lang.Random     
    String CUSTOM_IMPORTS = args[1].equals("-") ? "" : args[1];
    //Package of your Key serializer class. Use com.axiomine.bigcollections.functions
    String KPACKAGE = args[2];
    //Package of your value serializer class. Use com.axiomine.bigcollections.functions
    String VPACKAGE = args[3];
    //Class name (no packages) of the Key class Ex. String
    String K = args[4];
    //Class name (no packages) of the value class Ex. Integer
    String V = args[5];

    String kCls = K;
    String vCls = V;

    if (kCls.equals("byte[]")) {
        kCls = "BytesArray";
    }
    if (vCls.equals("byte[]")) {
        vCls = "BytesArray";
    }

    String CLASS_NAME = kCls + vCls + "Map"; //Default
    //String templatePath = args[5];
    File root = new File("");
    File outFile = new File(root.getAbsolutePath() + "/src/main/java/" + MY_PACKAGE.replaceAll("\\.", "/") + "/"
            + CLASS_NAME + ".java");

    if (outFile.exists()) {
        System.out.println(outFile.getAbsolutePath() + " already exists. Please delete it and try again");
    }
    {
        String[] imports = null;
        String importStr = "";

        if (!StringUtils.isBlank(CUSTOM_IMPORTS)) {
            CUSTOM_IMPORTS.split(":");
            for (String s : imports) {
                importStr = "import " + s + ";\n";
            }
        }

        String program = FileUtils.readFileToString(
                new File(root.getAbsolutePath() + "/src/main/resources/JavaLangBasedMapTemplate.java"));

        program = program.replaceAll("#MY_PACKAGE#", MY_PACKAGE);
        program = program.replaceAll("#CUSTOM_IMPORTS#", importStr);

        program = program.replaceAll("#CLASS_NAME#", CLASS_NAME);
        program = program.replaceAll("#K#", K);
        program = program.replaceAll("#V#", V);
        program = program.replaceAll("#KCLS#", kCls);
        program = program.replaceAll("#VCLS#", vCls);

        program = program.replaceAll("#KPACKAGE#", KPACKAGE);
        program = program.replaceAll("#VPACKAGE#", VPACKAGE);
        System.out.println(outFile.getAbsolutePath());
        FileUtils.writeStringToFile(outFile, program);
    }
}