java.io.BufferedWriter Java Examples
The following examples show how to use
java.io.BufferedWriter.
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: HDFS.java From incubator-retired-pirk with Apache License 2.0 | 6 votes |
public static void writeFile(List<BigInteger> elements, FileSystem fs, Path path, boolean deleteOnExit) { try { // create writer BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fs.create(path, true))); // write each element on a new line for (BigInteger element : elements) { bw.write(element.toString()); bw.newLine(); } bw.close(); // delete file once the filesystem is closed if (deleteOnExit) { fs.deleteOnExit(path); } } catch (IOException e) { e.printStackTrace(); } }
Example #2
Source File: LogImpl.java From RxZhihuDaily with MIT License | 6 votes |
private static boolean outputToFile(String message, String path) { if (TextUtils.isEmpty(message)) { return false; } if (TextUtils.isEmpty(path)) { return false; } boolean written = false; try { BufferedWriter fw = new BufferedWriter(new FileWriter(path, true)); fw.write(message); fw.flush(); fw.close(); written = true; } catch (Exception e) { e.printStackTrace(); } return written; }
Example #3
Source File: Scrobbler.java From lastfm-java with BSD 2-Clause "Simplified" License | 6 votes |
/** * Submits 'now playing' information. This does not affect the musical profile of the user. * * @param artist The artist's name * @param track The track's title * @param album The album or <code>null</code> * @param length The length of the track in seconds * @param tracknumber The position of the track in the album or -1 * @return the status of the operation * @throws IOException on I/O errors */ public ResponseStatus nowPlaying(String artist, String track, String album, int length, int tracknumber) throws IOException { if (sessionId == null) throw new IllegalStateException("Perform successful handshake first."); String b = album != null ? encode(album) : ""; String l = length == -1 ? "" : String.valueOf(length); String n = tracknumber == -1 ? "" : String.valueOf(tracknumber); String body = String .format("s=%s&a=%s&t=%s&b=%s&l=%s&n=%s&m=", sessionId, encode(artist), encode(track), b, l, n); if (Caller.getInstance().isDebugMode()) System.out.println("now playing: " + body); HttpURLConnection urlConnection = Caller.getInstance().openConnection(nowPlayingUrl); urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(true); OutputStream outputStream = urlConnection.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream)); writer.write(body); writer.close(); InputStream is = urlConnection.getInputStream(); BufferedReader r = new BufferedReader(new InputStreamReader(is)); String status = r.readLine(); r.close(); return new ResponseStatus(ResponseStatus.codeForStatus(status)); }
Example #4
Source File: TomlConfigFileDefaultProviderTest.java From besu with Apache License 2.0 | 6 votes |
@Test public void invalidConfigContentMustThrow() throws IOException { exceptionRule.expect(ParameterException.class); exceptionRule.expectMessage( "Invalid TOML configuration: Unexpected '=', expected ', \", ''', " + "\"\"\", a number, a boolean, a date/time, an array, or a table (line 1, column 19)"); final File tempConfigFile = temp.newFile("config.toml"); try (final BufferedWriter fileWriter = Files.newBufferedWriter(tempConfigFile.toPath(), UTF_8)) { fileWriter.write("an-invalid-syntax=======...."); fileWriter.flush(); final TomlConfigFileDefaultProvider providerUnderTest = new TomlConfigFileDefaultProvider(mockCommandLine, tempConfigFile); providerUnderTest.defaultValue(OptionSpec.builder("an-option").type(String.class).build()); } }
Example #5
Source File: IndexerUtilities.java From samantha with MIT License | 6 votes |
public static void writeCSVFields(JsonNode entity, List<String> curFields, BufferedWriter writer, String separator) throws IOException { ObjectMapper mapper = new ObjectMapper(); List<String> fields = new ArrayList<>(curFields.size()); for (String field : curFields) { String value; if (!entity.has(field)) { logger.warn("The field {} is not present in {}. Filled in with empty string.", field, entity); value = mapper.writeValueAsString(""); } else { value = mapper.writeValueAsString(entity.get(field)); } if (value.contains(separator)) { logger.warn("The field {} from {} already has the separator {}. Removed.", field, entity, separator); value = value.replace(separator, ""); } fields.add(StringEscapeUtils.unescapeCsv(value)); } String line = StringUtils.join(fields, separator); writer.write(line); writer.newLine(); writer.flush(); }
Example #6
Source File: LexicalUnitsFrameExtraction.java From semafor-semantic-parser with GNU General Public License v3.0 | 6 votes |
public static void semEvalTest() throws Exception { Arrays.sort(FramesSemEval.testSet); sentenceNum = 0; BufferedWriter bWriterFrames = new BufferedWriter(new FileWriter("/mal2/dipanjan/experiments/FramenetParsing/framenet_1.3/ddData/semeval.fulltest.sentences.frames")); BufferedWriter bWriterFEs = new BufferedWriter(new FileWriter("/mal2/dipanjan/experiments/FramenetParsing/framenet_1.3/ddData/semeval.fulltest.sentences.frame.elements")); for(int j = 0; j < FramesSemEval.testSet.length; j ++) { String fileName = FramesSemEval.testSet[j]; System.out.println("\n\n"+fileName); getSemEvalFrames(fileName,bWriterFrames); getSemEvalFrameElements(fileName,bWriterFEs); } bWriterFrames.close(); bWriterFEs.close(); }
Example #7
Source File: GFInputFormatJUnitTest.java From gemfirexd-oss with Apache License 2.0 | 6 votes |
@Override protected void configureHdfsStoreFactory() throws Exception { super.configureHdfsStoreFactory(); configFile = new File("testGFInputFormat-config"); String hadoopClientConf = "<configuration>\n " + " <property>\n " + " <name>dfs.block.size</name>\n " + " <value>2048</value>\n " + " </property>\n " + " <property>\n " + " <name>fs.default.name</name>\n " + " <value>hdfs://127.0.0.1:" + CLUSTER_PORT + "</value>\n" + " </property>\n " + " <property>\n " + " <name>dfs.replication</name>\n " + " <value>1</value>\n " + " </property>\n " + "</configuration>"; BufferedWriter bw = new BufferedWriter(new FileWriter(configFile)); bw.write(hadoopClientConf); bw.close(); hsf.setHDFSClientConfigFile(configFile.getName()); }
Example #8
Source File: TrpIobBuilder.java From TranskribusCore with GNU General Public License v3.0 | 6 votes |
private void addBeginningTag(CustomTag temp, BufferedWriter textLinebw, boolean exportProperties) throws IOException { if(temp.getTagName().equals("person")) { textLinebw.write("\tB-PER\tO"); if(exportProperties) { addPropsToFile(temp, textLinebw); } }else if(temp.getTagName().equals("place")){ textLinebw.write("\tB-LOC\tO"); if(exportProperties) { addPropsToFile(temp, textLinebw); } }else if(temp.getTagName().equals("organization")){ textLinebw.write("\tB-ORG\tO"); if(exportProperties) { addPropsToFile(temp, textLinebw); } }else if(temp.getTagName().equals("human_production")){ textLinebw.write("\tB-HumanProd\tO"); if(exportProperties) { addPropsToFile(temp, textLinebw); } } }
Example #9
Source File: IeeeCdfReaderWriterTest.java From powsybl-core with Mozilla Public License 2.0 | 6 votes |
private void testIeeeFile(String fileName) throws IOException { IeeeCdfModel model; // read try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/" + fileName)))) { model = new IeeeCdfReader().read(reader); } // write Path file = fileSystem.getPath("/work/" + fileName); try (BufferedWriter writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) { new IeeeCdfWriter(model).write(writer); } // read IeeeCdfModel model2; try (BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) { model2 = new IeeeCdfReader().read(reader); } String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(model); String json2 = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(model2); assertEquals(json, json2); }
Example #10
Source File: Rebanker.java From easyccg with MIT License | 6 votes |
private void writeCatList(Multiset<Category> cats, File outputFile) throws IOException { Multiset<Category> catsNoPPorPRfeatures = HashMultiset.create(); for (Category cat : cats) { catsNoPPorPRfeatures.add(cat.dropPPandPRfeatures()); } FileWriter fw = new FileWriter(outputFile.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); int categories = 0; for (Category type : Multisets.copyHighestCountFirst(cats).elementSet()) { if (catsNoPPorPRfeatures.count(type.dropPPandPRfeatures()) >= 10) { bw.write(type.toString()); bw.newLine(); categories++; } } System.out.println("Number of cats occurring 10 times: " + categories); bw.flush(); bw.close(); }
Example #11
Source File: ApplicationLogMaintainer.java From OneTapVideoDownload with GNU General Public License v3.0 | 6 votes |
void writeToLog(String message, boolean appendMode) { try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.US); String time = sdf.format(new Date()); message = time + " - " + message; File logFile = new File(getLogFilePath()); if (!logFile.getParentFile().exists()) { //noinspection ResultOfMethodCallIgnored logFile.getParentFile().mkdirs(); } BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(logFile, appendMode)); bufferedWriter.newLine(); bufferedWriter.append(message); bufferedWriter.close(); } catch (IOException e) { Log.e(TAG, "Exception in writeToLog", e); } }
Example #12
Source File: BaseLNPTestCase.java From teammates with GNU General Public License v2.0 | 6 votes |
/** * Creates the CSV data and writes it to the file specified by {@link #getCsvConfigPath()}. */ private void createCsvConfigDataFile(LNPTestData testData) throws IOException { List<String> headers = testData.generateCsvHeaders(); List<List<String>> valuesList = testData.generateCsvData(); String pathToCsvFile = createFileAndDirectory(TestProperties.LNP_TEST_DATA_FOLDER, getCsvConfigPath()); try (BufferedWriter bw = Files.newBufferedWriter(Paths.get(pathToCsvFile))) { // Write headers and data to the CSV file bw.write(convertToCsv(headers)); for (List<String> values : valuesList) { bw.write(convertToCsv(values)); } bw.flush(); } }
Example #13
Source File: TrainBatchModelDer.java From semafor-semantic-parser with GNU General Public License v3.0 | 6 votes |
public void saveModel(String modelFile) { try { BufferedWriter bWriter = new BufferedWriter(new FileWriter(modelFile)); for(int i = 0; i < modelSize; i ++) { bWriter.write(params[i]+"\n"); } bWriter.close(); } catch(Exception e) { e.printStackTrace(); } }
Example #14
Source File: AutoCodeGenerator.java From mPaaS with Apache License 2.0 | 6 votes |
private void writeApi() { String path = createDirFile("api", "api"); try (BufferedWriter apiInput = new BufferedWriter(new FileWriter(getJavaFilePath(path, this.apiName)))) { apiInput.write(getPackageLine("api", "api") + "\r\n"); apiInput.newLine(); apiInput.write(importPrefix("com.ibyte.common.core.api.IApi;") + "\r\n"); apiInput.write(getImportLine("dto", this.dtoName, "api") + "\r\n"); apiInput.newLine(); apiInput.write(buildComments()); apiInput.write(String.format("public interface %s extends IApi<%s> {", this.apiName, this.dtoName) + "\r\n"); apiInput.newLine(); apiInput.write("}"); } catch (IOException e) { e.printStackTrace(); } }
Example #15
Source File: PreloadSomeSuperTypesCache.java From glowroot with Apache License 2.0 | 6 votes |
private void appendNewLinesToFile() throws FileNotFoundException, IOException { BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), UTF_8)); try { int lineCount = 0; Iterator<String> i = needsToBeWritten.iterator(); while (i.hasNext()) { String typeName = i.next(); CacheValue cacheValue = checkNotNull(cache.get(typeName)); writeLine(out, typeName, cacheValue); lineCount++; } linesInFile += lineCount; } finally { out.close(); } }
Example #16
Source File: ExcitationEditorJFrame.java From opensim-gui with Apache License 2.0 | 6 votes |
private void jSaveTemplateMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jSaveTemplateMenuItemActionPerformed String fileName = FileUtils.getInstance().browseForFilenameToSave( FileUtils.getFileFilter(".txt", "Save layout to file"), true, "excitation_layout.txt", this); if(fileName!=null) { try { OutputStream ostream = new FileOutputStream(fileName); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(ostream)); ExcitationsGridJPanel gridPanel = dPanel.getExcitationGridPanel(); writer.write(gridPanel.getNumColumns()+"\n"); for(int i=0; i<gridPanel.getNumColumns(); i++) gridPanel.getColumn(i).write(writer); writer.flush(); writer.close(); } catch (IOException ex) { ErrorDialog.displayExceptionDialog(ex); } } // TODO add your handling code here: }
Example #17
Source File: MatrixVectorIoTest.java From matrix-toolkits-java with GNU Lesser General Public License v3.0 | 6 votes |
@Test public void testSparseWriteRead() throws Exception { CompRowMatrix mat = new CompRowMatrix(3, 3, new int[][]{{1, 2}, {0, 2}, {1}}); mat.set(0, 1, 1); mat.set(0, 2, 2); mat.set(1, 0, 3); mat.set(1, 2, 4); mat.set(2, 1, 5); File testFile = new File("TestMatrixFile"); testFile.deleteOnExit(); BufferedWriter out = new BufferedWriter(new FileWriter(testFile)); MatrixVectorWriter writer = new MatrixVectorWriter(out); MatrixInfo mi = new MatrixInfo(true, MatrixInfo.MatrixField.Real, MatrixInfo.MatrixSymmetry.General); writer.printMatrixInfo(mi); writer.printMatrixSize( new MatrixSize(mat.numColumns(), mat.numColumns(), mat .getData().length), mi); int[] rows = buildRowArray(mat); writer.printCoordinate(rows, mat.getColumnIndices(), mat.getData(), 1); out.close(); CompRowMatrix newMat = new CompRowMatrix(new MatrixVectorReader( new FileReader(testFile))); MatrixTestAbstract.assertMatrixEquals(mat, newMat); }
Example #18
Source File: QueryServlet.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Override protected void service(final WorkbenchRequest req, final HttpServletResponse resp, final String xslPath) throws IOException, RDF4JException, BadRequestException { if (!writeQueryCookie) { // If we suppressed putting the query text into the cookies before. cookies.addCookie(req, resp, REF, "hash"); String queryValue = req.getParameter(QUERY); String hash = String.valueOf(queryValue.hashCode()); queryCache.put(hash, queryValue); cookies.addCookie(req, resp, QUERY, hash); } if ("get".equals(req.getParameter("action"))) { ObjectNode jsonObject = mapper.createObjectNode(); jsonObject.put("queryText", getQueryText(req)); PrintWriter writer = new PrintWriter(new BufferedWriter(resp.getWriter())); try { writer.write(mapper.writeValueAsString(jsonObject)); } finally { writer.flush(); } } else { handleStandardBrowserRequest(req, resp, xslPath); } }
Example #19
Source File: Hdfs.java From pxf with Apache License 2.0 | 6 votes |
private void writeTableToStream(FSDataOutputStream stream, Table dataTable, String delimiter, Charset encoding) throws Exception { BufferedWriter bufferedWriter = new BufferedWriter( new OutputStreamWriter(stream, encoding)); List<List<String>> data = dataTable.getData(); for (int i = 0, flushThreshold = 0; i < data.size(); i++, flushThreshold++) { List<String> row = data.get(i); StringBuilder sBuilder = new StringBuilder(); for (int j = 0; j < row.size(); j++) { sBuilder.append(row.get(j)); if (j != row.size() - 1) { sBuilder.append(delimiter); } } if (i != data.size() - 1) { sBuilder.append("\n"); } bufferedWriter.append(sBuilder.toString()); if (flushThreshold > ROW_BUFFER) { bufferedWriter.flush(); } } bufferedWriter.close(); }
Example #20
Source File: DDHelper.java From netbeans with Apache License 2.0 | 6 votes |
public void run() { try { // PENDING : should be easier to define in layer and copy related FileObject (doesn't require systemClassLoader) if (toDir.getFileObject(toFile) != null) { return; // #229533, #189768: The file already exists in the file system --> Simply do nothing } FileObject xml = FileUtil.createData(toDir, toFile); String content = readResource(DDHelper.class.getResourceAsStream(fromFile)); if (content != null) { FileLock lock = xml.lock(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(xml.getOutputStream(lock))); try { bw.write(content); } finally { bw.close(); lock.releaseLock(); } } result = xml; } catch (IOException e) { exception = e; } }
Example #21
Source File: MiscTests.java From Robot-Overlord-App with GNU General Public License v2.0 | 6 votes |
/** * Used by plotXY() and plotXZ() * @param x * @param y * @param z * @param u * @param v * @param w * @param out * @param robot * @throws IOException */ private void plot(double x,double y,double z,double u,double v,double w,BufferedWriter out,Sixi2 robot) throws IOException { DHKeyframe keyframe0 = robot.sim.getIKSolver().createDHKeyframe(); Matrix4d m0 = new Matrix4d(); keyframe0.fkValues[0]=x; keyframe0.fkValues[1]=y; keyframe0.fkValues[2]=z; keyframe0.fkValues[3]=u; keyframe0.fkValues[4]=v; keyframe0.fkValues[5]=w; // use forward kinematics to find the endMatrix of the pose robot.sim.setPoseFK(keyframe0); m0.set(robot.sim.endEffector.getPoseWorld()); String message = StringHelper.formatDouble(m0.m03)+"\t" +StringHelper.formatDouble(m0.m13)+"\t" +StringHelper.formatDouble(m0.m23)+"\n"; out.write(message); }
Example #22
Source File: UnmatchedArgumentExceptionTest.java From picocli with Apache License 2.0 | 5 votes |
@Test public void testPrintSuggestionsPrintWriterAutoFlushes() { CommandLine cmd = new CommandLine(new Demo.GitCommit()); UnmatchedArgumentException ex = new UnmatchedArgumentException(cmd, Arrays.asList("-fi")); StringWriter sw = new StringWriter(); UnmatchedArgumentException.printSuggestions(ex, new PrintWriter(new BufferedWriter(sw))); String expected = format("" + "Possible solutions: --fixup, --file%n"); assertEquals(expected, sw.toString()); }
Example #23
Source File: BufferedWriterBenchmark.java From minimal-json with MIT License | 5 votes |
public void timeBufferedWriter(int reps) throws Exception { for (int i = 0; i < reps; i++) { ByteArrayOutputStream output = new ByteArrayOutputStream(); Writer writer = new BufferedWriter(new OutputStreamWriter(output)); runner.writeToWriter(model, writer); writer.close(); if (output.size() == 0) { throw new RuntimeException(); } } }
Example #24
Source File: ExpandedDAOIndexer.java From samantha with MIT License | 5 votes |
public ObjectNode getIndexedDataDAOConfig(RequestContext requestContext) { JsonNode reqBody = requestContext.getRequestBody(); try { EntityDAO entityDAO = EntityDAOUtilities.getEntityDAO(daoConfigs, requestContext, reqBody.get(daoConfigKey), injector); EntityDAO expandedDAO = new ExpandedEntityDAO(expanders, entityDAO, requestContext); BufferedWriter writer = new BufferedWriter(new FileWriter(cacheJsonFile)); while (expandedDAO.hasNextEntity()) { IndexerUtilities.writeJson(expandedDAO.getNextEntity(), writer); } expandedDAO.close(); writer.close(); } catch (IOException e) { throw new BadRequestException(e); } String start = JsonHelpers.getOptionalString(reqBody, beginTimeKey, beginTime); String end = JsonHelpers.getOptionalString(reqBody, endTimeKey, endTime); int startStamp = IndexerUtilities.parseTime(start); int endStamp = IndexerUtilities.parseTime(end); ObjectNode sub = Json.newObject(); sub.set(filePathKey, Json.toJson(cacheJsonFile)); sub.put(daoNameKey, subDaoName); ObjectNode ret = Json.newObject(); ret.put(daoNameKey, daoName); ret.put(beginTimeKey, Integer.valueOf(startStamp).toString()); ret.put(endTimeKey, Integer.valueOf(endStamp).toString()); ret.set(subDaoConfigKey, sub); return ret; }
Example #25
Source File: FreeMarkerExportHandler.java From pcgen with GNU Lesser General Public License v2.1 | 5 votes |
@Override public void write(PlayerCharacter aPC, BufferedWriter out) throws ExportException { File tFile = getTemplateFile(); if (tFile==null) { Logging.errorPrint("No template file selected - aborting."); return; } FileAccess.setCurrentOutputFilter(getTemplateFile().getName().substring(0, getTemplateFile().getName().length() - 4)); exportCharacterUsingFreemarker(aPC, out); }
Example #26
Source File: Content.java From zest-writer with GNU General Public License v3.0 | 5 votes |
public void saveToHtml(File file, MdTextController index) { try (FileOutputStream fos = new FileOutputStream(file)) { BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos, "UTF8")); String mdValue = exportContentToMarkdown(0, getDepth()); String htmlValue = StringEscapeUtils.unescapeHtml4(index.markdownToHtml(mdValue)); htmlValue = normalizeHtml(htmlValue); writer.append(MainApp.getMdUtils().addHeaderAndFooterStrict(htmlValue, getTitle())); writer.flush(); } catch (Exception e) { MainApp.getLogger().error(e.getMessage(), e); } }
Example #27
Source File: GeneralFileActionDemo.java From JavaBase with MIT License | 5 votes |
public static void writeFileToHDFS() throws IOException { Configuration configuration = new Configuration(); configuration.set("fs.defaultFS", "hdfs://localhost:9000"); FileSystem fileSystem = FileSystem.get(configuration); //Create a path String fileName = "read_write_hdfs_example.txt"; Path hdfsWritePath = new Path("/user/javadeveloperzone/javareadwriteexample/" + fileName); FSDataOutputStream fsDataOutputStream = fileSystem.create(hdfsWritePath, true); BufferedWriter bufferedWriter = new BufferedWriter( new OutputStreamWriter(fsDataOutputStream, StandardCharsets.UTF_8)); bufferedWriter.write("Java API to write data in HDFS"); bufferedWriter.newLine(); bufferedWriter.close(); fileSystem.close(); }
Example #28
Source File: CFileSettings.java From FxDock with Apache License 2.0 | 5 votes |
public void save(File f) throws Exception { FileTools.ensureParentFolder(f); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "8859_1")); try { save(out); } finally { CKit.close(out); } }
Example #29
Source File: WorldFileExporter.java From PyramidShader with GNU General Public License v3.0 | 5 votes |
public static void writeWorldFile(String worldFilePath, double cellSize, double west, double north) throws IOException { try (PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(worldFilePath)))) { writer.println(cellSize); writer.println(0); writer.println(0); writer.println(-cellSize); writer.println(west); writer.println(north); } }
Example #30
Source File: GuiConfiguration.java From ehacks-pro with GNU General Public License v3.0 | 5 votes |
@Override public void write() { try { FileWriter filewriter = new FileWriter(this.guiConfig); try (BufferedWriter buffered = new BufferedWriter(filewriter)) { GuiConfigJson configJson = new GuiConfigJson(); EHacksGui.clickGui.windows.forEach((window) -> { configJson.windows.put(window.getTitle().toLowerCase(), new WindowInfoJson(window)); }); buffered.write(new Gson().toJson(configJson)); } } catch (Exception e) { } }