List of usage examples for java.io BufferedWriter write
public void write(int c) throws IOException
From source file:org.opentides.util.FileUtil.java
/** * Helper class to append specified content to certain file. * /* ww w .j a v a 2 s. c o m*/ * @param filename * @param content * @return true if writing is successful */ public static void appendFile(String filename, String content) { BufferedWriter writer; try { writer = new BufferedWriter(new FileWriter(filename, true)); writer.write(content); writer.close(); } catch (IOException ioe) { String msg = "Cannot access file [" + filename + "]."; _log.error(ioe, ioe); throw new InvalidImplementationException(msg, ioe); } }
From source file:de.tudarmstadt.ukp.dkpro.tc.crfsuite.writer.CRFSuiteDataWriter.java
public static File writeFeatureFile(FeatureStore featureStore, File aOutputDirectory) throws Exception { int totalCountOfInstances = featureStore.getNumberOfInstances(); File outputFile = new File(aOutputDirectory, CRFSuiteAdapter.getInstance().getFrameworkFilename(AdapterNameEntries.featureVectorsFile)); outputFile.deleteOnExit();// w w w . j ava 2s. co m BufferedWriter bf = new BufferedWriter(new FileWriter(outputFile)); int lastSeenSeqId = -1; boolean seqIdChanged = false; for (int ins = 0; ins < totalCountOfInstances; ins++) { Instance i = featureStore.getInstance(ins); if (i.getSequenceId() != lastSeenSeqId) { seqIdChanged = true; lastSeenSeqId = i.getSequenceId(); } bf.write(LabelSubstitutor.labelReplacement(i.getOutcome())); bf.write("\t"); List<Feature> features = i.getFeatures(); for (int idx = 0; idx < features.size(); idx++) { Feature f = features.get(idx); bf.write(f.getName() + "=" + f.getValue()); if (idx + 1 < features.size()) { bf.write("\t"); } } // Mark first line of new sequence with an additional __BOS__ if (seqIdChanged) { bf.write("\t"); bf.write("__BOS__"); seqIdChanged = false; } // Peak ahead - seqEnd reached? if (ins + 1 < totalCountOfInstances) { Instance next = featureStore.getInstance(ins + 1); if (next.getSequenceId() != lastSeenSeqId) { appendEOS(bf); continue; } } else if (ins + 1 == totalCountOfInstances) { appendEOS(bf); } bf.write("\n"); } bf.close(); return outputFile; }
From source file:net.duckling.ddl.util.FileUtil.java
/** * Brief Intro Here/*from www.j a v a 2 s . com*/ * @param file ? * @param content ? * @param charset ? * @return ?? */ public static boolean writeFile(File file, String content, String charset) { try { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset)); bw.write(content); bw.flush(); bw.close(); return true; } catch (IOException e) { return false; } }
From source file:com.hmiard.blackwater.projects.Builder.java
/** * Building a new project.//www.j a v a 2 s .c o m * * @param projectName String * @param serverNames ArrayList * @param location String */ public static void buildNewProject(String projectName, ArrayList<String> serverNames, String location, ConsoleEmulator consoleListener) { try { consoleListener.clean(); consoleListener.push("Project creation started...\n\n"); projectName = projectName.substring(0, 1).toUpperCase() + projectName.substring(1); String projectUrl = location + "\\" + projectName; buildFolder(projectUrl); buildFolder(projectUrl + "\\bin"); buildFolder(projectUrl + "\\src"); buildFolder(projectUrl + "\\.blackwater"); ArrayList<String> realServerNames = new ArrayList<>(); for (String name : serverNames) realServerNames.add(name.replace("!", "")); // Creating the configuration Properties configuration = new Properties(); File tokens = new File(projectUrl + "\\.blackwater\\tokens.properties"); configuration.setProperty("PATH", projectUrl); configuration.setProperty("NAME", projectName); configuration.setProperty("SERVERS", Parser.parseArrayToStringList(",", realServerNames)); configuration.setProperty("LAST_UPDATE", new Date().toString()); configuration.store(new FileOutputStream(tokens), "Blackwater build version : " + Start.VERSION); consoleListener.push("Tokens generated.\n"); // Creating composer.json... JSONObject composerJSON = new JSONObject(); JSONObject autoload = new JSONObject(); JSONObject psr0 = new JSONObject(); JSONObject require = new JSONObject(); autoload.put("psr-0", psr0); composerJSON.put("autoload", autoload); composerJSON.put("require", require); require.put("blackwater/blackwaterp", Start.blackwaterpVersion); File composer = new File(projectUrl + "\\composer.json"); if (!composer.createNewFile()) { consoleListener.push("\nWeird composer stuff happened... Aborting.\n"); return; } BufferedWriter cw = new BufferedWriter(new FileWriter(composer.getAbsoluteFile())); String content = composerJSON.toString(4).replaceAll("\\\\", ""); cw.write(content); cw.close(); consoleListener.push("File created : composer.json\n"); // Creating the servers... consoleListener.push("Server creation started...\n"); for (String name : serverNames) if (name.charAt(0) == '!') appendServer(projectUrl, name.replace("!", ""), consoleListener, false); else appendServer(projectUrl, name, consoleListener, true); // Copying composer.phar consoleListener.push("Installing local composer wrapper...\n"); copyFile(new File("resources/packages/composer.phar"), new File(composer.getParent() + "\\bin\\composer.phar")); // Building... consoleListener.push("Building dependencies...\n"); new Thread(new ChildProcess("php bin/composer.phar install", composer.getParentFile(), consoleListener, () -> { NewProjectAppScreenPresenter presenter = (NewProjectAppScreenPresenter) consoleListener.app; presenter.projectCreatedCallback(projectUrl, consoleListener); })).start(); } catch (JSONException | IOException e) { e.printStackTrace(); } }
From source file:com.wakatime.intellij.plugin.WakaTime.java
private static void sendHeartbeat(final Heartbeat heartbeat, final ArrayList<Heartbeat> extraHeartbeats) { final String[] cmds = buildCliCommand(heartbeat, extraHeartbeats); log.debug("Executing CLI: " + Arrays.toString(obfuscateKey(cmds))); try {//ww w . ja va 2 s .co m Process proc = Runtime.getRuntime().exec(cmds); if (extraHeartbeats.size() > 0) { String json = toJSON(extraHeartbeats); log.debug(json); try { BufferedWriter stdin = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())); stdin.write(json); stdin.write("\n"); try { stdin.flush(); stdin.close(); } catch (IOException e) { /* ignored because wakatime-cli closes pipe after receiving \n */ } } catch (IOException e) { log.warn(e); } } if (WakaTime.DEBUG) { BufferedReader stdout = new BufferedReader(new InputStreamReader(proc.getInputStream())); BufferedReader stderr = new BufferedReader(new InputStreamReader(proc.getErrorStream())); proc.waitFor(); String s; while ((s = stdout.readLine()) != null) { log.debug(s); } while ((s = stderr.readLine()) != null) { log.debug(s); } log.debug("Command finished with return value: " + proc.exitValue()); } } catch (Exception e) { log.warn(e); } }
From source file:com.schnobosoft.semeval.cortical.PrintCorrelations.java
private static void saveCorrelations(File inputFile) throws IOException { assert inputFile.getName().startsWith(INPUT_FILE_PREFIX); File gsFile = new File(inputFile.getCanonicalPath().replace(INPUT_FILE_PREFIX, GS_FILE_PREFIX)); List<Optional> gs = readScoresFile(gsFile); File targetFile = new File(inputFile.getCanonicalPath() + ".cortical.scores"); BufferedWriter writer = new BufferedWriter(new FileWriter(targetFile)); LOG.info("Writing scores to " + targetFile); for (Retina retinaName : Retina.values()) { for (Measure correlationMeasure : Measure.values()) { File outputFile = getOutputFile(inputFile, correlationMeasure, retinaName); if (outputFile.exists()) { List<Optional> scores = readScoresFile(outputFile); double pearson = getPearson(gs, scores); writer.write(String.format("Pearson correlation (%s, %s):\t%.4f%n", retinaName.name().toLowerCase(), correlationMeasure, pearson)); } else { LOG.warn("Output file not found: " + outputFile); }/*from w w w . j a v a 2 s . c o m*/ } } writer.close(); }
From source file:com.hmiard.blackwater.projects.Builder.java
/** * Appending a new server to a project./*from w ww .j av a2 s . co m*/ * * @param projectRoot String * @param serverName String * @param consoleListener ConsoleEmulator * @param needsDb Boolean */ public static Boolean appendServer(String projectRoot, String serverName, ConsoleEmulator consoleListener, Boolean needsDb) { try { serverName = serverName.substring(0, 1).toUpperCase() + serverName.substring(1).toLowerCase(); String shortServerName = serverName; serverName += "Server"; String src = projectRoot + "\\src\\" + serverName; File checker = new File(projectRoot + "\\src\\" + serverName); File composerJSON = new File(projectRoot + "\\composer.json"); if (checker.exists() && checker.isDirectory()) { consoleListener.push("This server already exists ! Operation aborted."); return false; } if (!composerJSON.exists()) { consoleListener.push("File composer.json is missing ! Operation aborted."); return false; } if (needsDb) copyFolder(new File("resources/packages/DefaultApp"), new File(src)); else copyFolder(new File("resources/packages/NoDbApp"), new File(src)); FileOutputStream writer; File core = new File(src + "\\BlackwaterDefaultApp.php"); File qf = new File(src + "\\DefaultAppQueryFactory.php"); File bootstrap = new File(src + "\\bin\\init.php"); String coreContent = readFile(core.getAbsolutePath()); coreContent = coreContent.replace("BlackwaterDefaultApp", serverName); File newCore = new File(src + "\\" + serverName + ".php"); if (newCore.createNewFile() && core.delete()) { writer = new FileOutputStream(newCore); writer.write(coreContent.getBytes()); writer.flush(); writer.close(); } if (needsDb) { String qfContent = readFile(qf.getAbsolutePath()); qfContent = qfContent.replace("BlackwaterDefaultApp", serverName); qfContent = qfContent.replace("DefaultApp", shortServerName); File newQf = new File(src + "\\" + shortServerName + "QueryFactory.php"); if (newQf.createNewFile() && qf.delete()) { writer = new FileOutputStream(newQf); writer.write(qfContent.getBytes()); writer.flush(); writer.close(); } } String bootsrapContent = readFile(bootstrap.getAbsolutePath()); Random r = new Random(); bootsrapContent = bootsrapContent.replace("Default", shortServerName); bootsrapContent = bootsrapContent.replace("8080", String.valueOf(r.nextInt(2000) + 7000)); writer = new FileOutputStream(bootstrap); writer.write(bootsrapContent.getBytes()); writer.flush(); writer.close(); JSONObject composer = new JSONObject(readFile(composerJSON.getAbsolutePath())); JSONObject autoload = composer.getJSONObject("autoload"); JSONObject psr0 = autoload.getJSONObject("psr-0"); psr0.put(serverName, "src"); BufferedWriter cw = new BufferedWriter(new FileWriter(composerJSON.getAbsoluteFile())); String content = composer.toString(4).replaceAll("\\\\", ""); cw.write(content); cw.close(); consoleListener.push(serverName + " created !\n"); } catch (JSONException | IOException e) { e.printStackTrace(); } return true; }
From source file:com.murrayc.galaxyzoo.app.provider.client.ZooniverseClient.java
private static void writeParamsToHttpPost(final HttpURLConnection conn, final List<NameValuePair> nameValuePairs) throws IOException { OutputStream out = null;//from w w w . j av a2 s.c o m try { out = conn.getOutputStream(); BufferedWriter writer = null; try { writer = new BufferedWriter(new OutputStreamWriter(out, Utils.STRING_ENCODING)); writer.write(getPostDataBytes(nameValuePairs)); writer.flush(); } finally { if (writer != null) { writer.close(); } } } finally { if (out != null) { try { out.close(); } catch (final IOException e) { Log.error("writeParamsToHttpPost(): Exception while closing out", e); } } } }
From source file:net.semanticmetadata.lire.utils.FileUtils.java
/** * Creates a text file containing all full paths to the images in the directory and its subdirectories. * * @param imageDirectory the directories where the images can be found. * @param outputFile the text file to be written (to) * @param append set to false to overwrite. * @return the number of images found / lines written the output file. * @throws IOException//from www.jav a 2s .co m */ public static int createImagefileList(File imageDirectory, File outputFile, boolean append) throws IOException { if (!imageDirectory.isDirectory()) return -1; int result = 0; Collection<File> files = org.apache.commons.io.FileUtils.listFiles(imageDirectory, new String[] { "jpg", "png", "PNG", "JPG" }, true); BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile, append)); for (File f : files) { bw.write(f.getAbsolutePath() + "\n"); result++; } bw.close(); return result; }
From source file:com.threecrickets.sincerity.util.IoUtil.java
/** * Writes lines to a file using UTF-8, overwriting its current contents if * it has any./*from w ww. j a va2 s.c o m*/ * <p> * Lines end in a newline character. * * @param file * The file * @param lines * The lines * @throws IOException * In case of an I/O error */ public static void writeLines(File file, Iterable<String> lines) throws IOException { // Possible bug? // See: // http://tripoverit.blogspot.com/2007/04/javas-utf-8-and-unicode-writing-is.html FileOutputStream stream = new FileOutputStream(file); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream, StandardCharsets.UTF_8), BUFFER_SIZE); try { for (String line : lines) { writer.write(line); writer.write('\n'); } } catch (IOException x) { throw x; } finally { try { stream.close(); } catch (IOException x) { } } }