Example usage for java.io FileWriter FileWriter

List of usage examples for java.io FileWriter FileWriter

Introduction

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

Prototype

public FileWriter(FileDescriptor fd) 

Source Link

Document

Constructs a FileWriter given a file descriptor, using the platform's java.nio.charset.Charset#defaultCharset() default charset .

Usage

From source file:dk.lnj.swagger4ee.AbstractJSonTest.java

public void makeCompare(SWRoot root, String expFile) throws IOException {

    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
    // make deserializer use JAXB annotations (only)
    mapper.setAnnotationIntrospector(introspector);
    // make serializer use JAXB annotations (only)

    StringWriter sw = new StringWriter();
    mapper.writeValue(sw, root);/*from  w  w  w.  java2  s  . c o  m*/
    mapper.writeValue(new FileWriter(new File("lasttest.json")), root);

    String actual = sw.toString();
    String expected = new String(Files.readAllBytes(Paths.get(expFile)));

    String[] exp_split = expected.split("\n");
    String[] act_split = actual.split("\n");

    for (int i = 0; i < exp_split.length; i++) {
        String exp = exp_split[i];
        String act = act_split[i];
        String shortFileName = expFile.substring(expFile.lastIndexOf("/"));
        Assert.assertEquals(shortFileName + ":" + (i + 1), superTrim(exp), superTrim(act));
    }

}

From source file:com.iciql.test.IciqlSuite.java

/**
 * Main entry point for the test suite. Executing this method will run the
 * test suite on all registered databases.
 * //from  w ww . j  a  va  2s  .c  om
 * @param args
 * @throws Exception
 */
public static void main(String... args) throws Exception {
    Params params = new Params();
    JCommander jc = new JCommander(params);
    try {
        jc.parse(args);
    } catch (ParameterException t) {
        usage(jc, t);
    }

    // Replace System.out with a file
    if (!StringUtils.isNullOrEmpty(params.dbPerformanceFile)) {
        out = new PrintStream(params.dbPerformanceFile);
        System.setErr(out);
    }

    deleteRecursively(new File("testdbs"));

    // Start the HSQL and H2 servers in-process
    org.hsqldb.Server hsql = startHSQL();
    org.h2.tools.Server h2 = startH2();

    // Statement logging
    final FileWriter statementWriter;
    if (StringUtils.isNullOrEmpty(params.sqlStatementsFile)) {
        statementWriter = null;
    } else {
        statementWriter = new FileWriter(params.sqlStatementsFile);
    }
    IciqlListener statementListener = new IciqlListener() {
        @Override
        public void logIciql(StatementType type, String statement) {
            if (statementWriter == null) {
                return;
            }
            try {
                statementWriter.append(statement);
                statementWriter.append('\n');
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };
    IciqlLogger.registerListener(statementListener);

    SuiteClasses suiteClasses = IciqlSuite.class.getAnnotation(SuiteClasses.class);
    long quickestDatabase = Long.MAX_VALUE;
    String dividerMajor = buildDivider('*', 79);
    String dividerMinor = buildDivider('-', 79);

    // Header
    out.println(dividerMajor);
    out.println(MessageFormat.format("{0} {1} ({2}) testing {3} database configurations", Constants.NAME,
            Constants.VERSION, Constants.VERSION_DATE, TEST_DBS.length));
    out.println(dividerMajor);
    out.println();

    showProperty("java.vendor");
    showProperty("java.runtime.version");
    showProperty("java.vm.name");
    showProperty("os.name");
    showProperty("os.version");
    showProperty("os.arch");
    showProperty("available processors", "" + Runtime.getRuntime().availableProcessors());
    showProperty("available memory", MessageFormat.format("{0,number,0.0} GB",
            ((double) Runtime.getRuntime().maxMemory()) / (1024 * 1024)));
    out.println();

    // Test a database
    long lastCount = 0;
    for (TestDb testDb : TEST_DBS) {
        out.println(dividerMinor);
        out.println("Testing " + testDb.describeDatabase());
        out.println("        " + testDb.url);
        out.println(dividerMinor);

        // inject a database section delimiter in the statement log
        if (statementWriter != null) {
            statementWriter.append("\n\n");
            statementWriter.append("# ").append(dividerMinor).append('\n');
            statementWriter.append("# ").append("Testing " + testDb.describeDatabase()).append('\n');
            statementWriter.append("# ").append(dividerMinor).append('\n');
            statementWriter.append("\n\n");
        }

        if (testDb.getVersion().equals("OFFLINE")) {
            // Database not available
            out.println("Skipping.  Could not find " + testDb.url);
            out.println();
        } else {
            // Setup system properties
            System.setProperty("iciql.url", testDb.url);
            System.setProperty("iciql.user", testDb.username);
            System.setProperty("iciql.password", testDb.password);

            // Test database
            Result result = JUnitCore.runClasses(suiteClasses.value());

            // Report results
            testDb.runtime = result.getRunTime();
            if (testDb.runtime < quickestDatabase) {
                quickestDatabase = testDb.runtime;
            }
            testDb.statements = IciqlLogger.getTotalCount() - lastCount;
            // reset total count for next database
            lastCount = IciqlLogger.getTotalCount();

            out.println(MessageFormat.format(
                    "{0} tests ({1} failures, {2} ignores)  {3} statements in {4,number,0.000} secs",
                    result.getRunCount(), result.getFailureCount(), result.getIgnoreCount(), testDb.statements,
                    result.getRunTime() / 1000f));

            if (result.getFailureCount() == 0) {
                out.println();
                out.println("  100% successful test suite run.");
                out.println();
            } else {
                for (Failure failure : result.getFailures()) {
                    out.println(MessageFormat.format("\n  + {0}\n    {1}", failure.getTestHeader(),
                            failure.getMessage()));
                }
                out.println();
            }
        }
    }

    // Display runtime results sorted by performance leader
    out.println();
    out.println(dividerMajor);
    out.println(MessageFormat.format("{0} {1} ({2}) test suite performance results", Constants.NAME,
            Constants.VERSION, Constants.VERSION_DATE));
    out.println(dividerMajor);
    List<TestDb> dbs = Arrays.asList(TEST_DBS);
    Collections.sort(dbs);

    out.println(MessageFormat.format("{0} {1} {2} {3} {4}", StringUtils.pad("Name", 11, " ", true),
            StringUtils.pad("Type", 5, " ", true), StringUtils.pad("Version", 23, " ", true),
            StringUtils.pad("Stats/Sec", 10, " ", true), "Runtime"));
    out.println(dividerMinor);
    for (TestDb testDb : dbs) {
        DecimalFormat df = new DecimalFormat("0.0");
        out.println(MessageFormat.format("{0} {1} {2}   {3} {4} {5}s  ({6,number,0.0}x)",
                StringUtils.pad(testDb.name, 11, " ", true), testDb.isEmbedded ? "E" : "T",
                testDb.isMemory ? "M" : "F", StringUtils.pad(testDb.getVersion(), 21, " ", true),
                StringUtils.pad("" + testDb.getStatementRate(), 10, " ", false),
                StringUtils.pad(df.format(testDb.getRuntime()), 8, " ", false),
                ((double) testDb.runtime) / quickestDatabase));
    }
    out.println(dividerMinor);
    out.println("  E = embedded connection");
    out.println("  T = tcp/ip connection");
    out.println("  M = memory database");
    out.println("  F = file/persistent database");

    // cleanup
    for (PoolableConnectionFactory factory : connectionFactories.values()) {
        factory.getPool().close();
    }
    IciqlLogger.unregisterListener(statementListener);
    out.close();
    System.setErr(ERR);
    if (statementWriter != null) {
        statementWriter.close();
    }
    hsql.stop();
    h2.stop();
    System.exit(0);
}

From source file:au.org.ala.layers.util.BatchProducer.java

private static void writeToFile(String filename, String string) throws IOException {
    FileWriter fw = new FileWriter(filename);
    fw.write(string);/*from ww w. j  a  v a2  s . c  o m*/
    fw.close();
}

From source file:LoadSave.java

public static void doSaveCommand(JTextComponent textComponent, String filename) throws Exception {
    FileWriter writer = null;/*from  ww w. j  a v a2s  . c  o m*/
    writer = new FileWriter(filename);
    textComponent.write(writer);
    writer.close();
}

From source file:com.linkedin.pinot.core.data.readers.JSONRecordReaderTest.java

@BeforeClass
public void setUp() throws Exception {
    FileUtils.forceMkdir(TEMP_DIR);//from w w w. ja v  a  2  s.co  m

    try (FileWriter fileWriter = new FileWriter(DATA_FILE)) {
        for (Object[] record : RECORDS) {
            JSONObject jsonRecord = new JSONObject();
            if (record[0] != null) {
                jsonRecord.put(COLUMNS[0], record[0]);
            }
            if (record[1] != null) {
                jsonRecord.put(COLUMNS[1], new JSONArray(record[1]));
            }
            fileWriter.write(jsonRecord.toString());
        }
    }
}

From source file:com.a544jh.kanamemory.io.JsonFileWriter.java

/**
 * Saves the PlayerProfile to a JSON-formatted file. If the file exists, the
 * profile is added to the existing JSON-mapping, if a profile with the same
 * name already exists in th file, it will be overwritten. If the files does
 * not exist, a new JSON-formatted file will be created.
 *
 * @param profile The PlayerProfile to be saved.
 * @param filename The file to save the data to. Can be a JSON-formatted
 * file created by this method, or an nonexistent file.
 *///from w  w  w . j  a  v a 2s . co  m
public static void saveProfile(PlayerProfile profile, String filename) {
    File file = new File(filename);
    JSONObject jo = null;

    //Create a new file if it doesn't exist
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException ex) {
            Logger.getLogger(JsonFileWriter.class.getName()).log(Level.SEVERE, null, ex);
        }
        //Create new empty JSONObject
        jo = new JSONObject();
    } else {
        //If the file exists
        try {
            //Read the JSONObject from the file
            jo = JsonFileReader.readFileToJsonObject(file);
        } catch (FileNotFoundException | JSONException ex) {
            Logger.getLogger(JsonFileWriter.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    try {
        //Put the profile's scores to be saved in the JSONOBject with the name as key
        jo.put(profile.getName(), profile.getScoresMap());
        //Write the actual file
        try (FileWriter writer = new FileWriter(file)) {
            writer.write(jo.toString(4));
        }
    } catch (JSONException | IOException ex) {
        Logger.getLogger(JsonFileWriter.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.android.internal.http.multipart.MultipartTest.java

public void testParts() throws Exception {
    StringBuffer filebuffer = new StringBuffer();
    String filepartStr = "this is file part";
    filebuffer.append(filepartStr);/*from www.j a  v a2  s.c  o  m*/
    File upload = File.createTempFile("Multipart", "test");

    FileWriter outFile = new FileWriter(upload);
    BufferedWriter out = new BufferedWriter(outFile);
    try {
        out.write(filebuffer.toString());
        out.flush();
    } finally {
        out.close();
    }

    Part[] parts = new Part[3];
    parts[0] = new StringPart("stringpart", "PART1!!");
    parts[1] = new FilePart(upload.getName(), upload);
    parts[2] = new StringPart("stringpart", "PART2!!");

    MultipartEntity me = new MultipartEntity(parts);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    me.writeTo(os);
    Header h = me.getContentType();
    String boundry = EncodingUtils.getAsciiString(me.getMultipartBoundary());
    StringBuffer contentType = new StringBuffer("multipart/form-data");
    contentType.append("; boundary=");
    contentType.append(boundry);
    assertEquals("Multipart content type error", contentType.toString(), h.getValue());
    final String CRLF = "\r\n";
    StringBuffer output = new StringBuffer();

    output.append("--");
    output.append(boundry);
    output.append(CRLF);

    output.append("Content-Disposition: form-data; name=\"stringpart\"");
    output.append(CRLF);
    output.append("Content-Type: text/plain; charset=US-ASCII");
    output.append(CRLF);
    output.append("Content-Transfer-Encoding: 8bit");
    output.append(CRLF);
    output.append(CRLF);
    output.append("PART1!!");
    output.append(CRLF);

    output.append("--");
    output.append(boundry);
    output.append(CRLF);

    output.append("Content-Disposition: form-data; name=\"");
    output.append(upload.getName());
    output.append("\"; filename=\"");
    output.append(upload.getName());
    output.append("\"");

    output.append(CRLF);
    output.append("Content-Type: application/octet-stream; charset=ISO-8859-1");
    output.append(CRLF);
    output.append("Content-Transfer-Encoding: binary");
    output.append(CRLF);
    output.append(CRLF);
    output.append(filepartStr);
    output.append(CRLF);

    output.append("--");
    output.append(boundry);
    output.append(CRLF);

    output.append("Content-Disposition: form-data; name=\"stringpart\"");
    output.append(CRLF);
    output.append("Content-Type: text/plain; charset=US-ASCII");
    output.append(CRLF);
    output.append("Content-Transfer-Encoding: 8bit");
    output.append(CRLF);
    output.append(CRLF);
    output.append("PART2!!");
    output.append(CRLF);

    output.append("--");
    output.append(boundry);
    output.append("--");
    output.append(CRLF);
    // System.out.print(output.toString());
    assertEquals("Multipart content error", output.toString(), os.toString());

    // System.out.print(os.toString());
}

From source file:bammerbom.ultimatecore.spongeapi.resources.classes.ErrorLogger.java

public static void log(Throwable t, String s) {
    String time = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss-SSS").format(Calendar.getInstance().getTime());
    File dir = new File(r.getUC().getDataFolder() + "/Errors");
    if (!dir.exists()) {
        dir.mkdir();/*  w  ww  .ja v a2 s .c o m*/
    }
    File file = new File(r.getUC().getDataFolder() + "/Errors", time + ".txt");
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    FileWriter outFile;
    try {
        outFile = new FileWriter(file);
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }
    PrintWriter out = new PrintWriter(outFile);
    out.println("=======================================");
    out.println("UltimateCore has run into an error ");
    out.println("Please report your error on dev.bukkit.org/bukkit-plugins/ultimate_core/create-ticket");
    out.println("Spongeapi version: " + r.getGame().getMinecraftVersion() + " - "
            + r.getGame().getImplementationVersion());
    out.println("UltimateCore version: "
            + r.getGame().getPluginManager().getPlugin("UltimateCore").get().getVersion());
    out.println("Plugins loaded (" + r.getGame().getPluginManager().getPlugins().size() + "): "
            + Arrays.asList(r.getGame().getPluginManager().getPlugins()));
    out.println("Java version: " + System.getProperty("java.version"));
    out.println("OS info: " + System.getProperty("os.arch") + ", " + System.getProperty("os.name") + ", "
            + System.getProperty("os.version"));
    if (r.getGame().getServer().isPresent()) {
        out.println("Online mode: " + r.getGame().getServer().get().getOnlineMode());
    }
    out.println("Time: " + time);
    out.println("Error message: " + t.getMessage());
    out.println("UltimateCore message: " + s);
    out.println("=======================================");
    out.println("Stacktrace: \n" + ExceptionUtils.getStackTrace(t));
    out.println("=======================================");
    out.close();
    try {
        outFile.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    //
    r.log(" ");
    r.log(TextColors.DARK_RED + "=========================================================");
    r.log(TextColors.RED + "UltimateCore has run into an error ");
    r.log(TextColors.RED + "Please report your error on ");
    r.log(TextColors.YELLOW + "http://dev.bukkit.org/bukkit-plugins/ultimate_core/create-ticket");
    r.log(TextColors.RED + "Include the file: ");
    r.log(TextColors.YELLOW + "plugins/UltimateCore/Errors/" + time + ".txt ");
    /*r.log(TextColors.RED + "Sponge version: " + Bukkit.getServer().getVersion());
     r.log(TextColors.RED + "UltimateCore version: " + Bukkit.getPluginManager().getPlugin("UltimateCore").getDescription().getVersion());
     r.log(TextColors.RED + "Plugins loaded (" + Bukkit.getPluginManager().getPlugins().length + "): " + Arrays.asList(Bukkit.getPluginManager().getPlugins()));
     r.log(TextColors.RED + "Java version: " + System.getProperty("java.version"));
     r.log(TextColors.RED + "OS info: " + System.getProperty("os.arch") + ", " + System.getProperty("os.name") + ", " + System.getProperty("os.version"));
     r.log(TextColors.RED + "Error message: " + t.getMessage());
     r.log(TextColors.RED + "UltimateCore message: " + s);*/
    r.log(TextColors.DARK_RED + "=========================================================");
    if (t instanceof Exception) {
        r.log(TextColors.RED + "Stacktrace: ");
        t.printStackTrace();
        r.log(TextColors.DARK_RED + "=========================================================");
    }
    r.log(" ");
}

From source file:com.magnet.mmx.tsung.GenTestScript.java

public static void generateScripts(Settings settings) throws TemplateException {
    genSettings = settings;//  ww w  .  java 2  s  .c  om
    File file = new File(settings.outputDir + "/userdb.csv");
    FileWriter fileWriter = null;
    try {
        fileWriter = new FileWriter(file);
        // hard-code to "test" for all passwords
        String password = "test";
        for (int i = 1; i <= settings.maxCount; i++) {
            String jid = settings.userName + i + "%" + settings.appId;
            int random = new Random().nextInt(settings.maxCount); // make sure it's at least 1
            if (random == 0)
                random++;
            String toJid = settings.userName + random + "%" + settings.appId;
            // jid;password;toJid
            StringBuilder rowBuilder = new StringBuilder();
            rowBuilder.append(jid).append(";").append(password).append(";").append(toJid).append("\n");
            fileWriter.write(rowBuilder.toString());
        }
        fileWriter.close();

        // generate the login load test file
        generateLoginScript(settings);

        // generate the dev registration files
        generateDevRegScript(settings);

        // generate the message send files
        generateSendMessageScript(settings);

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:common.Utilities.java

public static boolean writeStringToFile(String filename, String stringToWrite) {
    try {//from www  . ja  va  2 s  . c  o  m
        FileWriter writer = new FileWriter(new File(filename));
        BufferedWriter bw = new BufferedWriter(writer);
        bw.write(stringToWrite);
        bw.flush();
        bw.close();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}