Java Code Examples for java.io.FileWriter#close()

The following examples show how to use java.io.FileWriter#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FastenKafkaPlugin.java    From fasten with Apache License 2.0 6 votes vote down vote up
/**
 * Writes {@link RevisionCallGraph} to JSON file and return JSON object containing
 * a link to to written file.
 *
 * @param result String of JSON representation of {@link RevisionCallGraph}
 * @return Path to a newly written JSON file
 */
private String writeToFile(String result)
        throws IOException, NullPointerException {
    var path = plugin.getOutputPath();
    var pathWithoutFilename = path.substring(0, path.lastIndexOf(File.separator));

    File directory = new File(this.writeDirectory + pathWithoutFilename);
    if (!directory.exists() && !directory.mkdirs()) {
        throw new IOException("Failed to create parent directories");
    }

    File file = new File(this.writeDirectory + path);
    FileWriter fw = new FileWriter(file.getAbsoluteFile());
    fw.write(result);
    fw.flush();
    fw.close();

    JSONObject link = new JSONObject();
    link.put("dir", file.getAbsolutePath());

    if (this.writeLink != null && !this.writeLink.equals("")) {
        link.put("link", this.writeLink + path);
    }
    return link.toString();
}
 
Example 2
Source File: Runner.java    From greycat with Apache License 2.0 6 votes vote down vote up
private static void save() throws Exception {
    final JsonObject runBench = new JsonObject();
    runBench.add("benchmarks", JsonHandler.global);
    runBench.add("time", System.currentTimeMillis());

    if (System.getProperty("commit") != null) {
        runBench.add("commit", System.getProperty("commit"));
    }
    if (System.getProperty("data") != null) {
        File targetDir = new File(System.getProperty("data"));
        if (!targetDir.exists()) {
            targetDir.mkdirs();
        }
        File output = new File(targetDir, System.currentTimeMillis() + ".json");
        FileWriter writer = new FileWriter(output);
        runBench.writeTo(writer);
        writer.flush();
        writer.close();
    } else {
        System.out.println(runBench.toString());
    }
}
 
Example 3
Source File: CreateConfigFileForSettingDefaultProduct.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Main logic to create config.ini file in ${target_home}/configuration folder
 */
public static void main(String[] args) throws IOException {
	if (args.length < 2) {
		return;
	}

	String targetHome = args[0];
	String defaultProductId = args[1];

	String folderPath = targetHome + File.separatorChar + "configuration";
	File folder = new File(folderPath);
	if (!folder.exists())
		folder.mkdirs();

	String filePath = folderPath + File.separatorChar + "config.ini";
	File file = new File(filePath);

	// Create the file config.ini
	if (!file.createNewFile()) {
		System.out.println("File " + filePath + " already exists.\n"
				+ "By default, the product to run is set to " + defaultProductId);
		return;
	}

	FileWriter writer = new FileWriter(file);
	writer.write("eclipse.product=" + defaultProductId);
	writer.close();

	System.out.println("File" + filePath + " has been created successfully!\n"
			+ "By default, the product to run is set to " + defaultProductId);
}
 
Example 4
Source File: Initializer.java    From hmdm-server with Apache License 2.0 5 votes vote down vote up
/**
 * <p>Signals on application initialization completion.</p>
 */
private void onInitializationCompletion(StringWriter errorOut) {

    final String signalFilePath = this.context.getInitParameter("initialization.completion.signal.file");
    if (signalFilePath != null && !signalFilePath.trim().isEmpty()) {
        File signalFile  = new File(signalFilePath);
        if (!signalFile.exists()) {
            try {
                FileWriter fw = new FileWriter(signalFile);
                PrintWriter pw = new PrintWriter(fw);
                if (errorOut == null) {
                    pw.print("OK");
                } else {
                    pw.print(errorOut.toString());
                }
                pw.close();
                fw.close();
                System.out.println("[HMDM-INITIALIZER]: Created a signal file for application " +
                        "initialization completion: " + signalFile.getAbsolutePath());
            } catch (IOException e) {
                System.err.println("[HMDM-INITIALIZER]: Failed to create and write to signal file '" + signalFile.getAbsolutePath()
                        + "' for application initialization completion" + e);
            }
        } else {
            System.out.println("[HMDM-INITIALIZER]: The signal file for application initialization completion " +
                    "already exists: " + signalFile.getAbsolutePath());
        }
    } else {
        System.out.println("Could not find 'initialization.completion.signal.file' parameter in context. " +
                "Signaling on application initialization completion will be skipped.");
    }
}
 
Example 5
Source File: CGenerator.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Generate C code. This method only creates the requested file(s)
 * and spits-out file-level elements (such as include statements etc.)
 * record-level code is generated by JRecord.
 */
@Override
void genCode(String name, ArrayList<JFile> ilist,
             ArrayList<JRecord> rlist, String destDir, ArrayList<String> options)
  throws IOException {
  name = new File(destDir, (new File(name)).getName()).getAbsolutePath();
  FileWriter cc = new FileWriter(name+".c");
  try {
    FileWriter hh = new FileWriter(name+".h");
    try {
      hh.write("#ifndef __"+
          StringUtils.toUpperCase(name).replace('.','_')+"__\n");
      hh.write("#define __"+
          StringUtils.toUpperCase(name).replace('.','_')+"__\n");
      hh.write("#include \"recordio.h\"\n");
      for (Iterator<JFile> iter = ilist.iterator(); iter.hasNext();) {
        hh.write("#include \""+iter.next().getName()+".h\"\n");
      }

      cc.write("#include \""+name+".h\"\n");

      /*
      for (Iterator<JRecord> iter = rlist.iterator(); iter.hasNext();) {
      iter.next().genCppCode(hh, cc);
      }
       */

      hh.write("#endif //"+
          StringUtils.toUpperCase(name).replace('.','_')+"__\n");
    } finally {
      hh.close();
    }
  } finally {
    cc.close();
  }
}
 
Example 6
Source File: OnThrowTest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        OnThrowTest myTest = new OnThrowTest();

        String launch = System.getProperty("test.classes") +
                        File.separator + "OnThrowLaunch.sh";
        File f = new File(launch);
        f.delete();
        FileWriter fw = new FileWriter(f);
        fw.write("#!/bin/sh\n echo OK $* > " +
                 myTest.touchFile.replace('\\','/') + "\n exit 0\n");
        fw.flush();
        fw.close();
        if ( ! f.exists() ) {
            throw new Exception("Test failed: sh file not created: " + launch);
        }

        String javaExe = System.getProperty("java.home") +
                         File.separator + "bin" + File.separator + "java";
        String targetClass = "OnThrowTarget";
        String cmds [] = {javaExe,
                          "-agentlib:jdwp=transport=dt_socket," +
                          "onthrow=OnThrowException,server=y,suspend=n," +
                          "launch=" + "sh " + launch.replace('\\','/'),
                          targetClass};

        /* Run the target app, which will launch the launch script */
        myTest.run(cmds);
        if ( !myTest.touchFileExists() ) {
            throw new Exception("Test failed: touch file not found: " +
                  myTest.touchFile);
        }

        System.out.println("Test passed: launch create file");
    }
 
Example 7
Source File: Watchdog.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private void doSysRq(char c) {
    try {
        FileWriter sysrq_trigger = new FileWriter("/proc/sysrq-trigger");
        sysrq_trigger.write(c);
        sysrq_trigger.close();
    } catch (IOException e) {
        Slog.w(TAG, "Failed to write to /proc/sysrq-trigger", e);
    }
}
 
Example 8
Source File: ConsoleManager.java    From tbschedule with Apache License 2.0 5 votes vote down vote up
public static void saveConfigInfo(Properties p) throws Exception {
    FileWriter writer = new FileWriter(CONFIG_FILE);
    p.store(writer, "");
    writer.close();
    if (scheduleManagerFactory == null) {
        initial();
    } else {
        scheduleManagerFactory.reInit(p);
    }
}
 
Example 9
Source File: PepperBoxLoadGenTest.java    From pepper-box with Apache License 2.0 5 votes vote down vote up
@Test
public void consoleLoadGenTest() throws IOException {
    File schemaFile = File.createTempFile("json", ".schema");
    schemaFile.deleteOnExit();
    FileWriter schemaWriter = new FileWriter(schemaFile);
    schemaWriter.write(TestInputUtils.testSchema);
    schemaWriter.close();

    File producerFile = File.createTempFile("producer", ".properties");
    producerFile.deleteOnExit();
    FileWriter producerPropsWriter = new FileWriter(producerFile);
    producerPropsWriter.write(String.format(TestInputUtils.producerProps, BROKERHOST, BROKERPORT, ZKHOST, zkServer.port()));
    producerPropsWriter.close();

    String vargs []  = new String[]{"--schema-file", schemaFile.getAbsolutePath(), "--producer-config-file", producerFile.getAbsolutePath(), "--throughput-per-producer", "10", "--test-duration", "1", "--num-producers", "1"};
    PepperBoxLoadGenerator.main(vargs);

    Properties consumerProps = new Properties();
    consumerProps.setProperty("bootstrap.servers", BROKERHOST + ":" + BROKERPORT);
    consumerProps.setProperty("group.id", "group");
    consumerProps.setProperty("key.deserializer","org.apache.kafka.common.serialization.StringDeserializer");
    consumerProps.setProperty("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
    consumerProps.put("auto.offset.reset", "earliest");
    KafkaConsumer<String, String> consumer = new KafkaConsumer<>(consumerProps);
    consumer.subscribe(Arrays.asList(TOPIC));
    ConsumerRecords<String, String> records = consumer.poll(30000);
    Assert.assertTrue("PepperBoxLoadGenerator validation failed", records.count() > 0);

}
 
Example 10
Source File: Logger.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void api(String message) {
	String timeStamp = new SimpleDateFormat("yyyy/MM/dd-HH:mm:ss").format(Calendar.getInstance().getTime());

	try {
		FileWriter file = new FileWriter(apiFile, true);
		file.write("API --- " + timeStamp + " ---" + GlobalConst.lineBreak);
		file.write("info: " + message + GlobalConst.lineBreak);
		file.close();
	} catch (IOException io) {
		io.printStackTrace();
	}
}
 
Example 11
Source File: NativeKeyboard.java    From SpyGen with Apache License 2.0 5 votes vote down vote up
public void onSave() {
    try {
        FileWriter fw = new FileWriter(Settings.KEYLOGGER_PATH + "logs_" + new Date().toString().replace(" ", "_").replace(":", "-") + ".txt");
        fw.write(typedCache.toString());
        fw.close();

        typedCache = new StringBuilder(); // clean cache
    } catch(IOException ioe) {
        ioe.printStackTrace();
    }
}
 
Example 12
Source File: Logger.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void api(String message, String ip, String host, String endpoint) {
	String timeStamp = new SimpleDateFormat("yyyy/MM/dd-HH:mm:ss").format(Calendar.getInstance().getTime());

	try {
		FileWriter file = new FileWriter(apiFile, true);
		file.write("API --- " + timeStamp + " ---" + GlobalConst.lineBreak);
		file.write("info: " + message + GlobalConst.lineBreak);
		file.write("IP: " + ip + GlobalConst.lineBreak);
		file.write("Host: " + host + GlobalConst.lineBreak);
		file.write("Endpoint: " + endpoint + GlobalConst.lineBreak);
		file.close();
	} catch (IOException io) {
		io.printStackTrace();
	}
}
 
Example 13
Source File: PropertiesDefaultProviderTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Ignore
@Test
public void testArgGroups() throws IOException {
    File temp = File.createTempFile("MyCommand", ".properties");
    FileWriter fw = new FileWriter(temp);
    fw.write("myCommand.x=6\n" +
            "myCommand.y=9\n" +
            "myCommand.myOption=9\n");
    fw.flush();
    fw.close();

    CommandLine cmd = new CommandLine(new CommandIssue876());
    cmd.setDefaultValueProvider(new PropertiesDefaultProvider(temp));
    cmd.execute();
}
 
Example 14
Source File: TestHostsFileReader.java    From hadoop with Apache License 2.0 4 votes vote down vote up
@Test
public void testHostFileReaderWithCommentsOnly() throws Exception {
  FileWriter efw = new FileWriter(excludesFile);
  FileWriter ifw = new FileWriter(includesFile);

  efw.write("#DFS-Hosts-excluded\n");
  efw.close();

  ifw.write("#Hosts-in-DFS\n");
  ifw.close();

  HostsFileReader hfp = new HostsFileReader(includesFile, excludesFile);

  int includesLen = hfp.getHosts().size();
  int excludesLen = hfp.getExcludedHosts().size();

  assertEquals(0, includesLen);
  assertEquals(0, excludesLen);

  assertFalse(hfp.getHosts().contains("somehost5"));

  assertFalse(hfp.getExcludedHosts().contains("somehost5"));

}
 
Example 15
Source File: GrobidPDFProcessor.java    From science-result-extractor with Apache License 2.0 4 votes vote down vote up
public void writeFullTextTEIXml(String pdfStr, String xmlFileStr) throws IOException, Exception {
    String xml = getFullTextToTEI(pdfStr);
    FileWriter writer = new FileWriter(new File(xmlFileStr));
    writer.write(xml);
    writer.close();
}
 
Example 16
Source File: JsHint.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@TaskAction
public void doJsHint() {
    RhinoWorkerHandleFactory handleFactory = new DefaultRhinoWorkerHandleFactory(workerProcessBuilderFactory);

    LogLevel logLevel = getProject().getGradle().getStartParameter().getLogLevel();
    RhinoWorkerHandle<JsHintResult, JsHintSpec> rhinoHandle = handleFactory.create(getRhinoClasspath(), createWorkerSpec(), logLevel, new Action<JavaExecSpec>() {
        public void execute(JavaExecSpec javaExecSpec) {
            javaExecSpec.setWorkingDir(getProject().getProjectDir());
        }
    });

    JsHintSpec spec = new JsHintSpec();
    spec.setSource(getSource().getFiles()); // flatten because we need to serialize
    spec.setEncoding(getEncoding());
    spec.setJsHint(getJsHint().getSingleFile());

    JsHintResult result = rhinoHandle.process(spec);
    setDidWork(true);

    // TODO - this is all terribly lame. We need some proper reporting here (which means implementing Reporting).

    Logger logger = getLogger();
    boolean anyErrors = false;

    Map<String, Map<?, ?>> reportData = new LinkedHashMap<String, Map<?, ?>>(result.getResults().size());
    for (Map.Entry<File, Map<String, Object>> fileEntry: result.getResults().entrySet()) {
        File file = fileEntry.getKey();
        Map<String, Object> data = fileEntry.getValue();

        reportData.put(file.getAbsolutePath(), data);

        if (data.containsKey("errors")) {
            anyErrors = true;

            URI projectDirUri = getProject().getProjectDir().toURI();
            @SuppressWarnings("unchecked") Map<String, Object> errors = (Map<String, Object>) data.get("errors");
            if (!errors.isEmpty()) {
                URI relativePath = projectDirUri.relativize(file.toURI());
                logger.warn("JsHint errors for file: {}", relativePath.getPath());
                for (Map.Entry<String, Object> errorEntry : errors.entrySet()) {
                    @SuppressWarnings("unchecked") Map<String, Object> error = (Map<String, Object>) errorEntry.getValue();
                    int line = Float.valueOf(error.get("line").toString()).intValue();
                    int character = Float.valueOf(error.get("character").toString()).intValue();
                    String reason = error.get("reason").toString();

                    logger.warn("  {}:{} > {}", new Object[] {line, character, reason});
                }
            }
        }
    }

    File jsonReportFile = getJsonReport();
    if (jsonReportFile != null) {
        try {
            FileWriter reportWriter = new FileWriter(jsonReportFile);
            new GsonBuilder().setPrettyPrinting().create().toJson(reportData, reportWriter);
            reportWriter.close();
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    if (anyErrors) {
        throw new TaskExecutionException(this, new GradleException("JsHint detected errors"));
    }
}
 
Example 17
Source File: Simple.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Generates TimeZoneData to output SimpleTimeZone data.
 * @param map Mappings object which is generated by {@link Main#compile}.
 * @return 0 if no error occurred, otherwise 1.
 */
int generateSrc(Mappings map) {
    try {
        File outD = new File(Main.getOutputDir());
        outD.mkdirs();

        FileWriter fw =
            new FileWriter(new File(outD, "TimeZoneData.java"), false);
        BufferedWriter out = new BufferedWriter(fw);

        out.write("import java.util.SimpleTimeZone;\n\n");
        out.write("    static SimpleTimeZone zones[] = {\n");

        Map<String,String> a = map.getAliases();
        List<Integer> roi = map.getRawOffsetsIndex();
        List<Set<String>> roit = map.getRawOffsetsIndexTable();

        int index = 0;
        for (int offset : zonesByOffset.keySet()) {
            int o = roi.get(index);
            Set<String> set = zonesByOffset.get(offset);
            if (offset == o) {
                // Merge aliases into zonesByOffset
                set.addAll(roit.get(index));
            }
            index++;

            for (String key : set) {
                ZoneRec zrec;
                String realname;
                List<RuleRec> stz;
                if ((realname = a.get(key)) != null) {
                    // if this alias is not targeted, ignore it.
                    if (!Zone.isTargetZone(key)) {
                        continue;
                    }
                    stz = lastRules.get(realname);
                    zrec = lastZoneRecs.get(realname);
                } else {
                    stz = lastRules.get(key);
                    zrec = lastZoneRecs.get(key);
                }

                out.write("\t//--------------------------------------------------------------------\n");
                String s = Time.toFormedString(offset);
                out.write("\tnew SimpleTimeZone(" +
                    Time.toFormedString(offset) + ", \"" + key + "\"");
                if (realname != null) {
                    out.write(" /* " + realname + " */");
                }

                if (stz == null) {
                    out.write("),\n");
                } else {
                    RuleRec rr0 = stz.get(0);
                    RuleRec rr1 = stz.get(1);

                    out.write(",\n\t  " + Month.toString(rr0.getMonthNum()) +
                              ", " + rr0.getDay().getDayForSimpleTimeZone() + ", " +
                              rr0.getDay().getDayOfWeekForSimpleTimeZone() + ", " +
                              Time.toFormedString((int)rr0.getTime().getTime()) + ", " +
                              rr0.getTime().getTypeForSimpleTimeZone() + ",\n" +

                              "\t  " + Month.toString(rr1.getMonthNum()) + ", " +
                              rr1.getDay().getDayForSimpleTimeZone() + ", " +
                              rr1.getDay().getDayOfWeekForSimpleTimeZone() + ", " +
                              Time.toFormedString((int)rr1.getTime().getTime())+ ", " +
                              rr1.getTime().getTypeForSimpleTimeZone() + ",\n" +

                              "\t  " + Time.toFormedString(rr0.getSave()) + "),\n");

                    out.write("\t// " + rr0.getLine() + "\n");
                    out.write("\t// " + rr1.getLine() + "\n");
                }

                String zline = zrec.getLine();
                if (zline.indexOf("Zone") == -1) {
                    zline = "Zone " + key + "\t" + zline.trim();
                }
                out.write("\t// " + zline + "\n");
            }
        }
        out.write("    };\n");

        out.close();
        fw.close();
    } catch(IOException e) {
        Main.panic("IO error: "+e.getMessage());
        return 1;
    }

    return 0;
}
 
Example 18
Source File: CharacterCategory.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
private static void generateTestProgram() {
    try {
        FileWriter fout = new FileWriter(outfile);
        BufferedWriter bout = new BufferedWriter(fout);

        bout.write(collationMethod);
        bout.write("\n    //\n    // The following arrays can be used in CharSet.java as is.\n    //\n\n");

        bout.write("    private static final String[] categoryNames = {");
        for (int i = 0; i < categoryNames.length - 1; i++) {
            if (i % 10 == 0) {
                bout.write("\n        ");
            }
            bout.write("\"" + categoryNames[i] + "\", ");
        }
        bout.write("\n    };\n\n");

        bout.write("    private static final int[][] categoryMap = {\n");

        for (int i = 0; i < categoryNames.length - 1; i++) {
            StringBuffer sb = new StringBuffer("        { /*  Data for \"" + categoryNames[i] + "\" category */");

            for (int j = 0; j < newTotalCount[i]; j++) {
                if (j % 8 == 0) {
                    sb.append("\n        ");
                }
                sb.append(" 0x");
                sb.append(Integer.toString(newList[i][j], 16).toUpperCase());
                sb.append(',');
            }
            sb.append("\n        },\n");
            bout.write(sb.toString());
        }

        bout.write("    };\n");

        bout.write("\n}\n");

        bout.close();
        fout.close();
    }
    catch (Exception e) {
        System.err.println("Error occurred on accessing " + outfile);
        e.printStackTrace();
        System.exit(1);
    }

    System.out.println("\n" + outfile + " has been generated.");
}
 
Example 19
Source File: EhDaoGenerator.java    From MHViewer with Apache License 2.0 4 votes vote down vote up
private static void adjustHistoryInfo() throws Exception {
    JavaClassSource javaClass = Roaster.parse(JavaClassSource.class, new File(HISTORY_INFO_PATH));
    // Remove field from GalleryInfo
    javaClass.removeField(javaClass.getField("gid"));
    javaClass.removeField(javaClass.getField("token"));
    javaClass.removeField(javaClass.getField("title"));
    javaClass.removeField(javaClass.getField("titleJpn"));
    javaClass.removeField(javaClass.getField("thumb"));
    javaClass.removeField(javaClass.getField("category"));
    javaClass.removeField(javaClass.getField("posted"));
    javaClass.removeField(javaClass.getField("uploader"));
    javaClass.removeField(javaClass.getField("rating"));
    javaClass.removeField(javaClass.getField("simpleLanguage"));
    // Set all field public
    javaClass.getField("mode").setPublic();
    javaClass.getField("time").setPublic();
    // Add Parcelable stuff
    javaClass.addMethod("\t@Override\n" +
            "\tpublic int describeContents() {\n" +
            "\t\treturn 0;\n" +
            "\t}");
    javaClass.addMethod("\t@Override\n" +
            "\tpublic void writeToParcel(Parcel dest, int flags) {\n" +
            "\t\tsuper.writeToParcel(dest, flags);\n" +
            "\t\tdest.writeInt(this.mode);\n" +
            "\t\tdest.writeLong(this.time);\n" +
            "\t}");
    javaClass.addMethod("\tprotected HistoryInfo(Parcel in) {\n" +
            "\t\tsuper(in);\n" +
            "\t\tthis.mode = in.readInt();\n" +
            "\t\tthis.time = in.readLong();\n" +
            "\t}").setConstructor(true);
    javaClass.addField("\tpublic static final Creator<HistoryInfo> CREATOR = new Creator<HistoryInfo>() {\n" +
            "\t\t@Override\n" +
            "\t\tpublic HistoryInfo createFromParcel(Parcel source) {\n" +
            "\t\t\treturn new HistoryInfo(source);\n" +
            "\t\t}\n" +
            "\n" +
            "\t\t@Override\n" +
            "\t\tpublic HistoryInfo[] newArray(int size) {\n" +
            "\t\t\treturn new HistoryInfo[size];\n" +
            "\t\t}\n" +
            "\t};");
    javaClass.addImport("com.axlecho.api.MHApiSource");
    javaClass.addImport("android.os.Parcel");
    // Add from GalleryInfo constructor
    javaClass.addMethod("\tpublic HistoryInfo(GalleryInfo galleryInfo) {\n" +
            "\t\tthis.source = galleryInfo.getId().split(\"@\")[1];\n" +
            "\t\tthis.gid = galleryInfo.gid;\n" +
            "\t\tthis.token = galleryInfo.token;\n" +
            "\t\tthis.title = galleryInfo.title;\n" +
            "\t\tthis.titleJpn = galleryInfo.titleJpn;\n" +
            "\t\tthis.thumb = galleryInfo.thumb;\n" +
            "\t\tthis.category = galleryInfo.category;\n" +
            "\t\tthis.posted = galleryInfo.posted;\n" +
            "\t\tthis.uploader = galleryInfo.uploader;\n" +
            "\t\tthis.rating = galleryInfo.rating;\n" +
            "\t\tthis.simpleTags = galleryInfo.simpleTags;\n" +
            "\t\tthis.simpleLanguage = galleryInfo.simpleLanguage;\n" +
            "\t\tthis.id = galleryInfo.getId();\n" +
            "\t}").setConstructor(true);
    javaClass.addImport("com.hippo.ehviewer.client.data.GalleryInfo");

    FileWriter fileWriter = new FileWriter(HISTORY_INFO_PATH);
    fileWriter.write(javaClass.toString());
    fileWriter.close();
}
 
Example 20
Source File: CharacterCategory.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
private static void generateTestProgram() {
    try {
        FileWriter fout = new FileWriter(outfile);
        BufferedWriter bout = new BufferedWriter(fout);

        bout.write(collationMethod);
        bout.write("\n    //\n    // The following arrays can be used in CharSet.java as is.\n    //\n\n");

        bout.write("    private static final String[] categoryNames = {");
        for (int i = 0; i < categoryNames.length - 1; i++) {
            if (i % 10 == 0) {
                bout.write("\n        ");
            }
            bout.write("\"" + categoryNames[i] + "\", ");
        }
        bout.write("\n    };\n\n");

        bout.write("    private static final int[][] categoryMap = {\n");

        for (int i = 0; i < categoryNames.length - 1; i++) {
            StringBuffer sb = new StringBuffer("        { /*  Data for \"" + categoryNames[i] + "\" category */");

            for (int j = 0; j < newTotalCount[i]; j++) {
                if (j % 8 == 0) {
                    sb.append("\n        ");
                }
                sb.append(" 0x");
                sb.append(Integer.toString(newList[i][j], 16).toUpperCase());
                sb.append(',');
            }
            sb.append("\n        },\n");
            bout.write(sb.toString());
        }

        bout.write("    };\n");

        bout.write("\n}\n");

        bout.close();
        fout.close();
    }
    catch (Exception e) {
        System.err.println("Error occurred on accessing " + outfile);
        e.printStackTrace();
        System.exit(1);
    }

    System.out.println("\n" + outfile + " has been generated.");
}