Here are the examples of the java api class java.io.BufferedWriter taken from open source projects.
1. Player#save()
Project: jmud
File: Player.java
File: Player.java
void save() throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(Global.getConfig().getUserFilesDir() + String.valueOf(getId()))); roomId = (thePlace == null) ? Room.NOWHERE : thePlace.getId(); writer.write(theName); writer.newLine(); writer.write(passPhrase); writer.newLine(); StrUtil.writeDescription(writer, theDescription); writer.write(StrUtil.makeFlags(preferences)); writer.newLine(); writer.write(roomId + " " + invisibilityRank); writer.newLine(); writer.write(theRank + " " + theLevel); writer.newLine(); writer.write(thePosition + " " + sex); writer.newLine(); writer.write(experience + " " + totalExperience); writer.newLine(); writer.write(goodBehavior + " " + badBehavior); writer.newLine(); writer.write(String.valueOf(fights) + " " + String.valueOf(kills) + " " + String.valueOf(deaths) + " " + String.valueOf(flees)); writer.newLine(); for (int r = 0; r < 5; ++r) { for (int c = 0; c < 4; ++c) writer.write(realAttr[r * 4 + c] + " "); writer.newLine(); } writer.write(stam + " " + will + " " + soul + " " + conf); writer.newLine(); money.save(writer); writer.write(StrUtil.headedConcat(recentHosts.elements(), " ")); writer.newLine(); writer.write(StrUtil.headedConcat(spells.elements(), new NameExtractor(), ",")); writer.newLine(); writer.write(StrUtil.headedConcat(jobs.elements(), new StringExtractor(), ",")); writer.newLine(); writer.write(StrUtil.headedConcat(abilities.elements(), new StringExtractor(), ",")); writer.newLine(); writer.write(Separators.EOF); writer.newLine(); writer.close(); }
2. TestTransformCommandCluster#createSourceDataset()
Project: kite
File: TestTransformCommandCluster.java
File: TestTransformCommandCluster.java
@BeforeClass public static void createSourceDataset() throws Exception { repoUri = "hdfs://" + getDFS().getUri().getAuthority() + "/tmp/data"; TestUtil.run("delete", source, "-r", repoUri, "-d", "target/data"); String csv = "target/users.csv"; BufferedWriter writer = Files.newWriter(new File(csv), CSVSchemaCommand.SCHEMA_CHARSET); writer.append("id,username,email\n"); writer.append("1,test,[email protected]\n"); writer.append("2,user,[email protected]\n"); writer.append("3,user3,[email protected]\n"); writer.append("4,user4,[email protected]\n"); writer.append("5,user5,[email protected]\n"); writer.append("6,user6,[email protected]\n"); writer.close(); TestUtil.run("-v", "csv-schema", csv, "-o", avsc, "--class", "User"); TestUtil.run("create", source, "-s", avsc, "-r", repoUri, "-d", "target/data"); TestUtil.run("csv-import", csv, source, "-r", repoUri, "-d", "target/data"); }
3. TestCopyCommandCluster#createSourceDataset()
Project: kite
File: TestCopyCommandCluster.java
File: TestCopyCommandCluster.java
@BeforeClass public static void createSourceDataset() throws Exception { repoUri = "hdfs://" + getDFS().getUri().getAuthority() + "/tmp/data"; TestUtil.run("delete", source, "-r", repoUri, "-d", "target/data"); String csv = "/tmp/users.csv"; BufferedWriter writer = Files.newWriter(new File(csv), CSVSchemaCommand.SCHEMA_CHARSET); writer.append("id,username,email\n"); writer.append("1,test,[email protected]\n"); writer.append("2,user,[email protected]\n"); writer.append("3,user3,[email protected]\n"); writer.append("4,user4,[email protected]\n"); writer.append("5,user5,[email protected]\n"); writer.append("6,user6,[email protected]\n"); writer.close(); TestUtil.run("-v", "csv-schema", csv, "-o", avsc, "--class", "User", "--require", "id"); TestUtil.run("create", source, "-s", avsc, "-r", repoUri, "-d", "target/data"); TestUtil.run("csv-import", csv, source, "-r", repoUri, "-d", "target/data"); }
4. BoxBlacklistParser#writeExamples()
Project: vsminecraft
File: BoxBlacklistParser.java
File: BoxBlacklistParser.java
private static void writeExamples() throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(boxBlacklistFile)); writer.append("# Use this file to tell Mekanism which blocks should not be picked up by a cardboard box."); writer.newLine(); writer.append("# Proper syntax is \"NAME:META\". Example (for stone):"); writer.newLine(); writer.append("# stone:0"); writer.flush(); writer.close(); }
5. DynamicFileConfigurationTest#createConfigFile()
Project: archaius
File: DynamicFileConfigurationTest.java
File: DynamicFileConfigurationTest.java
static File createConfigFile(String prefix) throws Exception { configFile = File.createTempFile(prefix, ".properties"); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(configFile), "UTF-8")); writer.write("dprops1=123456789"); writer.newLine(); writer.write("dprops2=79.98"); writer.newLine(); // this property should fail validation but should not affect update of other properties writer.write("abc=-2"); writer.newLine(); writer.close(); System.err.println(configFile.getPath() + " created"); return configFile; }
6. SentrySchemaTool#runBeeLine()
Project: incubator-sentry
File: SentrySchemaTool.java
File: SentrySchemaTool.java
// run beeline on the given sentry store scrip, flatten the nested scripts into single file private void runBeeLine(String scriptDir, String scriptFile) throws IOException { NestedScriptParser dbCommandParser = SentrySchemaHelper.getDbCommandParser(dbType); dbCommandParser.setDbOpts(getDbOpts()); // expand the nested script String sqlCommands = buildCommand(dbCommandParser, scriptDir, scriptFile); File tmpFile = File.createTempFile("schematool", ".sql"); tmpFile.deleteOnExit(); // write out the buffer into a file. Add beeline commands for autocommit and close FileWriter fstream = new FileWriter(tmpFile.getPath()); BufferedWriter out = new BufferedWriter(fstream); out.write("!set Silent " + verbose + System.getProperty("line.separator")); out.write("!autocommit on" + System.getProperty("line.separator")); out.write("!set Isolation TRANSACTION_READ_COMMITTED" + System.getProperty("line.separator")); out.write("!set AllowMultiLineCommand false" + System.getProperty("line.separator")); out.write(sqlCommands); out.write("!closeall" + System.getProperty("line.separator")); out.close(); runBeeLine(tmpFile.getPath()); }
7. TestCSVImportCommandCluster#testDirectoryImport()
Project: kite
File: TestCSVImportCommandCluster.java
File: TestCSVImportCommandCluster.java
@Test public void testDirectoryImport() throws Exception { new File("target/sample").mkdir(); BufferedWriter writer = Files.newWriter(new File("target/sample/one.csv"), CSVSchemaCommand.SCHEMA_CHARSET); writer.append("id,username,email\n"); writer.append("1,test,[email protected]\n"); writer.close(); writer = Files.newWriter(new File("target/sample/two.csv"), CSVSchemaCommand.SCHEMA_CHARSET); writer.append("id,username,email\n"); writer.append("2,user,[email protected]\n"); writer.close(); command.targets = Lists.newArrayList("target/sample", datasetName); command.run(); Assert.assertEquals("Should contain expected records", expected, DatasetTestUtilities.materialize(dataset)); verify(console).info("Added {} records to \"{}\"", 2l, datasetName); verifyNoMoreInteractions(console); }
8. TestCSVImportCommand#testDirectoryImport()
Project: kite
File: TestCSVImportCommand.java
File: TestCSVImportCommand.java
@Test public void testDirectoryImport() throws Exception { new File("target/sample").mkdir(); BufferedWriter writer = Files.newWriter(new File("target/sample/one.csv"), CSVSchemaCommand.SCHEMA_CHARSET); writer.append("id,username,email\n"); writer.append("1,test,[email protected]\n"); writer.close(); writer = Files.newWriter(new File("target/sample/two.csv"), CSVSchemaCommand.SCHEMA_CHARSET); writer.append("id,username,email\n"); writer.append("2,user,[email protected]\n"); writer.close(); command.targets = Lists.newArrayList("target/sample", datasetName); command.run(); Assert.assertEquals("Should contain expected records", expected, DatasetTestUtilities.materialize(dataset)); verify(console).trace(contains("repo:file:target/data")); verify(console).info("Added {} records to \"{}\"", 2l, datasetName); verifyNoMoreInteractions(console); }
9. GalenUtilsTest#shouldReadRelativePath()
Project: galen
File: GalenUtilsTest.java
File: GalenUtilsTest.java
@Test public void shouldReadRelativePath() throws Exception { File baseDir = new File(System.getProperty("java.io.tmpdir")); File tempDir = new File(baseDir, "galen_test"); tempDir.mkdir(); File testFile1 = new File(tempDir, "testFile.txt"); BufferedWriter output = new BufferedWriter(new FileWriter(testFile1)); output.write(""); output.close(); File testFile2 = new File(baseDir, "testFile2.txt"); BufferedWriter output2 = new BufferedWriter(new FileWriter(testFile2)); output2.write(""); output2.close(); InputStream fileStream1 = GalenUtils.findFileOrResourceAsStream(testFile1.getAbsolutePath()); assertThat(fileStream1, notNullValue()); InputStream fileStream2 = GalenUtils.findFileOrResourceAsStream(tempDir.toString() + File.separator + ".." + File.separator + "testFile2.txt"); assertThat(fileStream2, notNullValue()); FileUtils.deleteQuietly(tempDir); FileUtils.deleteQuietly(testFile2); }
10. TestFilePersistentFormatter#createPartFiles()
Project: lens
File: TestFilePersistentFormatter.java
File: TestFilePersistentFormatter.java
/** * Creates the part files. * * @throws IOException Signals that an I/O exception has occurred. */ @BeforeTest public void createPartFiles() throws IOException { // create csv files FileSystem fs = partFileDir.getFileSystem(new Configuration()); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fs.create(new Path(partFileDir, "000000_2")))); writer.write("\"1\",\"one\",\"one\",\"one\",\"1\",\"1:one\",\"1=one\"\n"); writer.close(); writer = new BufferedWriter(new OutputStreamWriter(fs.create(new Path(partFileDir, "000001_0")))); writer.write("\"2\",\"two\",\"two\",\"two\",\"1,2\",\"2:two\",\"1=one,2=two\"\n"); writer.write("\"NULL\",\"three\",\"three\",\"three\",\"1,2,NULL\",\"NULL:three\",\"1=one,2=two,NULL=three\"\n"); writer.close(); writer = new BufferedWriter(new OutputStreamWriter(fs.create(new Path(partFileDir, "000010_1")))); writer.write("\"4\",\"NULL\",\"NULL\",\"NULL\",\"1,2,NULL,4\",\"4:NULL\",\"1=one,2=two,NULL=three,4=NULL\"\n"); writer.write("\"NULL\",\"NULL\",\"NULL\",\"NULL\",\"1,2,NULL,4,NULL\",\"NULL:NULL\"," + "\"1=one,2=two,NULL=three,4=NULL,5=NULL\"\n"); writer.close(); writer = new BufferedWriter(new OutputStreamWriter(fs.create(new Path(partFileDir, "_SUCCESS")))); writer.close(); // create text files fs = partFileTextDir.getFileSystem(new Configuration()); writer = new BufferedWriter(new OutputStreamWriter(fs.create(new Path(partFileTextDir, "000000_2")))); writer.write("1oneoneone 11one1one \n"); writer.close(); writer = new BufferedWriter(new OutputStreamWriter(fs.create(new Path(partFileTextDir, "000001_0")))); writer.write("2twotwotwo 122two1one 2two \n"); writer.write("\\Nthreethreethree 12\\N\\Nthree1one 2two \\Nthree \n"); writer.close(); writer = new BufferedWriter(new OutputStreamWriter(fs.create(new Path(partFileTextDir, "000010_1")))); writer.write("4\\N\\N\\N12\\N44\\N1one 2two \\Nthree 4\\N\n"); writer.write("\\N\\N\\N\\N12\\N4\\N\\N\\N1one 2two \\Nthree 4\\N5\\N\n"); writer.close(); writer = new BufferedWriter(new OutputStreamWriter(fs.create(new Path(partFileTextDir, "_SUCCESS")))); writer.close(); }
11. DataTransform#generateHeaderFiles()
Project: incubator-systemml
File: DataTransform.java
File: DataTransform.java
public static void generateHeaderFiles(FileSystem fs, String txMtdDir, String origHeader, String newHeader) throws IOException { // write out given header line Path pt = new Path(txMtdDir + "/" + TfUtils.TXMTD_COLNAMES); BufferedWriter br = new BufferedWriter(new OutputStreamWriter(fs.create(pt, true))); br.write(origHeader + "\n"); br.close(); // write out the new header line (after all transformations) pt = new Path(txMtdDir + "/" + TfUtils.TXMTD_DC_COLNAMES); br = new BufferedWriter(new OutputStreamWriter(fs.create(pt, true))); br.write(newHeader + "\n"); br.close(); }
12. TestTransformCommandLocal#createSourceDataset()
Project: kite
File: TestTransformCommandLocal.java
File: TestTransformCommandLocal.java
@BeforeClass public static void createSourceDataset() throws Exception { TestUtil.run("delete", source, "--use-local", "-d", "target/data"); String csv = "target/users.csv"; BufferedWriter writer = Files.newWriter(new File(csv), CSVSchemaCommand.SCHEMA_CHARSET); writer.append("id,username,email\n"); writer.append("1,test,[email protected]\n"); writer.append("2,user,[email protected]\n"); writer.close(); TestUtil.run("-v", "csv-schema", csv, "-o", avsc, "--class", "User"); TestUtil.run("create", source, "-s", avsc, "--use-local", "-d", "target/data"); TestUtil.run("csv-import", csv, source, "--use-local", "-d", "target/data"); }
13. TestShowRecordsCommand#createDatasetFromCSV()
Project: kite
File: TestShowRecordsCommand.java
File: TestShowRecordsCommand.java
@BeforeClass public static void createDatasetFromCSV() throws Exception { String sample = "target/users.csv"; String avsc = "target/user.avsc"; BufferedWriter writer = Files.newWriter(new File(sample), CSVSchemaCommand.SCHEMA_CHARSET); writer.append("id,username,email\n"); writer.append("1,test,[email protected]\n"); writer.append("2,user,[email protected]\n"); writer.close(); TestUtil.run("delete", "users", "--use-local", "-d", "target/data"); TestUtil.run("-v", "csv-schema", sample, "-o", avsc, "--class", "User"); TestUtil.run("-v", "create", "users", "--use-local", "-d", "target/data", "-s", avsc); TestUtil.run("-v", "csv-import", sample, "--use-local", "-d", "target/data", "users"); }
14. TestCopyCommandLocal#createSourceDataset()
Project: kite
File: TestCopyCommandLocal.java
File: TestCopyCommandLocal.java
@BeforeClass public static void createSourceDataset() throws Exception { TestUtil.run("delete", source, "--use-local", "-d", "target/data"); String csv = "target/users.csv"; BufferedWriter writer = Files.newWriter(new File(csv), CSVSchemaCommand.SCHEMA_CHARSET); writer.append("id,username,email\n"); writer.append("1,test,[email protected]\n"); writer.append("2,user,[email protected]\n"); writer.close(); TestUtil.run("-v", "csv-schema", csv, "-o", avsc, "--class", "User"); TestUtil.run("create", source, "-s", avsc, "--use-local", "-d", "target/data"); TestUtil.run("csv-import", csv, source, "--use-local", "-d", "target/data"); }
15. OpenCalaisAnnotator#callServiceOnText()
Project: uima-addons
File: OpenCalaisAnnotator.java
File: OpenCalaisAnnotator.java
protected InputStream callServiceOnText(String modifiedText) throws IOException, UnsupportedEncodingException { URLConnection connection = this.calaisService.openConnection(); connection.setDoOutput(true); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8")); writer.write(this.serviceParams); for (int i = 0; i < this.charsToReplace.length; i++) { modifiedText = modifiedText.replaceAll(this.charsToReplace[i], ""); } modifiedText = modifiedText.replaceAll("\n", " "); modifiedText = modifiedText.replaceAll("\r", " "); if (this.getContext().getLogger().isLoggable(Level.INFO)) this.getContext().getLogger().log(Level.FINER, new StringBuilder(this.calaisService.toString()).append(this.serviceParams).append(modifiedText).toString()); writer.write(modifiedText); writer.flush(); writer.close(); return connection.getInputStream(); }
16. Gdb#sendCommand()
Project: che
File: Gdb.java
File: Gdb.java
private synchronized GdbOutput sendCommand(String command, boolean grabOutput) throws IOException, GdbTerminatedException, InterruptedException { LOG.debug(command); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream())); writer.write(command); writer.newLine(); writer.flush(); return grabOutput ? grabGdbOutput() : null; }
17. DefaultPropertiesPersister#doStore()
Project: bboss
File: DefaultPropertiesPersister.java
File: DefaultPropertiesPersister.java
protected void doStore(Properties props, Writer writer, String header) throws IOException { BufferedWriter out = new BufferedWriter(writer); if (header != null) { out.write("#" + header); out.newLine(); } out.write("#" + new Date()); out.newLine(); for (Enumeration keys = props.keys(); keys.hasMoreElements(); ) { String key = (String) keys.nextElement(); String val = props.getProperty(key); out.write(escape(key, true) + "=" + escape(val, false)); out.newLine(); } out.flush(); }
18. NewAccessKeyDialog#saveFile()
Project: aws-toolkit-eclipse
File: NewAccessKeyDialog.java
File: NewAccessKeyDialog.java
// Save the file private void saveFile(String fileName) throws IOException { File f = new File(fileName); // Check whether the file already exists. if (f.createNewFile() == false) { throw new IOException("File already exists " + fileName); } String content = ""; FileWriter fstream = new FileWriter(f.getAbsoluteFile()); BufferedWriter out = new BufferedWriter(fstream); out.write("\"User Name\",\"Access Key Id\",\"Secret Access Key\"\n"); content += "\"" + userName + "\","; content += "\"" + createAccessKeyResult.getAccessKey().getAccessKeyId() + "\","; content += "\"" + createAccessKeyResult.getAccessKey().getSecretAccessKey() + "\""; out.write(content); out.close(); }
19. MySQLUtils#writePasswordFile()
Project: sqoop
File: MySQLUtils.java
File: MySQLUtils.java
public static String writePasswordFile(Configuration conf) throws IOException { // Create the temp file to hold the user's password. String tmpDir = conf.get(ConfigurationConstants.PROP_JOB_LOCAL_DIRECTORY, "/tmp/"); File tempFile = File.createTempFile("mysql-cnf", ".cnf", new File(tmpDir)); // Make the password file only private readable. DirectImportUtils.setFilePermissions(tempFile, "0600"); // If we're here, the password file is believed to be ours alone. The // inability to set chmod 0600 inside Java is troublesome. We have to // trust that the external 'chmod' program in the path does the right // thing, and returns the correct exit status. But given our inability to // re-read the permissions associated with a file, we'll have to make do // with this. String password = DBConfiguration.getPassword((JobConf) conf); BufferedWriter w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile))); w.write("[client]\n"); w.write("password=" + password + "\n"); w.close(); return tempFile.toString(); }
20. OAuth2Client#postTokenEndpoint()
Project: sms-backup-plus
File: OAuth2Client.java
File: OAuth2Client.java
private HttpsURLConnection postTokenEndpoint(String payload) throws IOException { HttpsURLConnection connection = (HttpsURLConnection) new URL(TOKEN_URL).openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); final OutputStream os = connection.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(payload); writer.flush(); writer.close(); os.close(); return connection; }
21. PreferredResources#write()
Project: river
File: PreferredResources.java
File: PreferredResources.java
/** * Write the preferences to the specified OutputStream using the * preference list syntax. Preference expressions are written in * the following order: * * Complete name expressions * * Package expressions * * Namespace expressions * * @param out the stream to which formatted preference information * will be written * @throws IOException if an error occurs while writing to the stream */ public void write(OutputStream out) throws IOException { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out, "UTF8")); /* write the specification header */ bw.write(HEADER_TITLE + "1.0\n"); bw.write(PREF_PREFIX + " " + defaultPreference + "\n\n"); /* write out most specific preferences first */ writeMap(completeNamePrefs, bw, ""); writeMap(packagePrefs, bw, "/*"); writeMap(namespacePrefs, bw, "/-"); bw.flush(); }
22. XMLFormatter#format()
Project: redpen
File: XMLFormatter.java
File: XMLFormatter.java
@Override public void format(PrintWriter pw, Map<cc.redpen.model.Document, List<ValidationError>> docErrorsMap) throws RedPenException, IOException { BufferedWriter writer = new BufferedWriter(new PrintWriter(pw)); writer.write("<validation-result>\n"); for (cc.redpen.model.Document document : docErrorsMap.keySet()) { List<ValidationError> errors = docErrorsMap.get(document); for (ValidationError error : errors) { writer.write(formatError(document, error)); } } writer.write("</validation-result>"); writer.flush(); }
23. GroovyScriptTest#testClientLogging()
Project: gitblit
File: GroovyScriptTest.java
File: GroovyScriptTest.java
@Test public void testClientLogging() throws Exception { MockGitblit gitblit = new MockGitblit(); MockLogger logger = new MockLogger(); MockClientLogger clientLogger = new MockClientLogger(); List<ReceiveCommand> commands = new ArrayList<ReceiveCommand>(); commands.add(new ReceiveCommand(ObjectId.fromString("c18877690322dfc6ae3e37bb7f7085a24e94e887"), ObjectId.fromString("3fa7c46d11b11d61f1cbadc6888be5d0eae21969"), "refs/heads/master")); RepositoryModel repository = new RepositoryModel("[email protected]", "", "admin", new Date()); File groovyDir = repositories().getHooksFolder(); File tempScript = File.createTempFile("testClientLogging", "groovy", groovyDir); tempScript.deleteOnExit(); BufferedWriter writer = new BufferedWriter(new FileWriter(tempScript)); writer.write("clientLogger.info('this is a test message')\n"); writer.flush(); writer.close(); test(tempScript.getName(), gitblit, logger, clientLogger, commands, repository); assertTrue("Message Missing", clientLogger.messages.contains("this is a test message")); }
24. ModelCache#writeValueToDisk()
Project: frisbee
File: ModelCache.java
File: ModelCache.java
private void writeValueToDisk(OutputStream os, Object o) throws IOException { BufferedWriter out = new BufferedWriter(new OutputStreamWriter(os)); String className = o.getClass().getCanonicalName(); out.write(className + "\n"); String json = mGson.toJson(o); out.write(json); out.close(); }
25. TestCSVImportCommand#testIncompatibleSchemaFieldType()
Project: kite
File: TestCSVImportCommand.java
File: TestCSVImportCommand.java
@Test public void testIncompatibleSchemaFieldType() throws Exception { BufferedWriter writer = Files.newWriter(new File("target/incompatible.csv"), CSVSchemaCommand.SCHEMA_CHARSET); writer.append("id,username,email\n"); // id will be String writer.append("NaN,test,[email protected]\n"); writer.close(); // This will fail because NaN isn't a valid long and the field is required command.targets = Lists.newArrayList("target/incompatible.csv", datasetName); int rc = command.run(); Assert.assertEquals(1, rc); verify(console).trace(contains("repo:file:target/data")); verifyNoMoreInteractions(console); }
26. LocalMySQLManager#writePasswordFile()
Project: hadoop-mapreduce
File: LocalMySQLManager.java
File: LocalMySQLManager.java
private String writePasswordFile() throws IOException { // Create the temp file to hold the user's password. String tmpDir = options.getTempDir(); File tempFile = File.createTempFile("mysql-cnf", ".cnf", new File(tmpDir)); // Make the password file only private readable. DirectImportUtils.setFilePermissions(tempFile, "0600"); // If we're here, the password file is believed to be ours alone. // The inability to set chmod 0600 inside Java is troublesome. We have to trust // that the external 'chmod' program in the path does the right thing, and returns // the correct exit status. But given our inability to re-read the permissions // associated with a file, we'll have to make do with this. String password = options.getPassword(); BufferedWriter w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile))); w.write("[client]\n"); w.write("password=" + password + "\n"); w.close(); return tempFile.toString(); }
27. ZuulFilterPoller#writeFilterToDisk()
Project: zuul
File: ZuulFilterPoller.java
File: ZuulFilterPoller.java
private void writeFilterToDisk(FilterInfo newFilter) throws IOException { String path = DynamicPropertyFactory.getInstance().getStringProperty(ZuulConstants.ZUUL_FILTER_PRE_PATH, null).get(); if (newFilter.getFilterType().equals("post")) { path = DynamicPropertyFactory.getInstance().getStringProperty(ZuulConstants.ZUUL_FILTER_POST_PATH, null).get(); } if (newFilter.getFilterType().equals("route")) { path = DynamicPropertyFactory.getInstance().getStringProperty(ZuulConstants.ZUUL_FILTER_ROUTING_PATH, null).get(); } File f = new File(path, newFilter.getFilterName() + ".groovy"); FileWriter file = new FileWriter(f); BufferedWriter out = new BufferedWriter(file); out.write(newFilter.getFilterCode()); out.close(); file.close(); System.out.println("filter written " + f.getPath()); }
28. ExtensionScript#saveScript()
Project: zaproxy
File: ExtensionScript.java
File: ExtensionScript.java
public void saveScript(ScriptWrapper script) throws IOException { refreshScript(script); BufferedWriter fw = new BufferedWriter(new FileWriter(script.getFile(), false)); fw.append(script.getContents()); fw.close(); this.setChanged(script, false); // The removal is required for script that use wrappers, like Zest this.getScriptParam().removeScript(script); this.getScriptParam().addScript(script); this.getScriptParam().saveScripts(); for (ScriptEventListener listener : this.listeners) { try { listener.scriptSaved(script); } catch (Exception e) { logger.error(e.getMessage(), e); } } }
29. GitRepositoryTest#addCommit()
Project: yobi
File: GitRepositoryTest.java
File: GitRepositoryTest.java
public RevCommit addCommit(Git git, String fileName, String contents, String commitMessage, User author) throws IOException, GitAPIException { File newFile = new File(git.getRepository().getWorkTree().getAbsolutePath(), fileName); BufferedWriter out = new BufferedWriter(new FileWriter(newFile)); out.write(contents); out.flush(); git.add().addFilepattern(fileName).call(); CommitCommand commit = git.commit().setMessage(commitMessage); if (author != null) { commit.setAuthor(author.loginId, author.email).setCommitter(author.loginId, author.email); } return commit.call(); }
30. StringProvider#writeTo()
Project: wink
File: StringProvider.java
File: StringProvider.java
public void writeTo(String t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { mediaType = MediaTypeUtils.setDefaultCharsetOnMediaTypeHeader(httpHeaders, mediaType); Charset charset = Charset.forName(ProviderUtils.getCharset(mediaType)); OutputStreamWriter writer = new OutputStreamWriter(entityStream, charset); BufferedWriter bw = new BufferedWriter(writer); bw.write(t, 0, t.length()); bw.flush(); }
31. MockDirectoryManagerTest#createFileUsingOutputstream()
Project: Wikidata-Toolkit
File: MockDirectoryManagerTest.java
File: MockDirectoryManagerTest.java
@Test public void createFileUsingOutputstream() throws IOException { OutputStream out = mdm.getOutputStreamForFile("newfile.txt"); BufferedWriter ow = new BufferedWriter(new OutputStreamWriter(out)); ow.write("New contents"); ow.close(); String content = MockStringContentFactory.getStringFromInputStream(mdm.getInputStreamForFile("newfile.txt", CompressionType.NONE)); assertEquals("New contents", content); }
32. RealVoltDB#setupDefaultDeployment()
Project: voltdb
File: RealVoltDB.java
File: RealVoltDB.java
/** * Create default deployment.xml file in voltdbroot if the deployment path is null. * * @return path to default deployment file * @throws IOException */ static String setupDefaultDeployment(VoltLogger logger) throws IOException { // Since there's apparently no deployment to override the path to voltdbroot it should be // safe to assume it's under the working directory. // CatalogUtil.getVoltDbRoot() creates the voltdbroot directory as needed. File voltDbRoot = CatalogUtil.getVoltDbRoot(null); String pathToDeployment = voltDbRoot.getPath() + File.separator + "deployment.xml"; File deploymentXMLFile = new File(pathToDeployment); logger.info("Generating default deployment file \"" + deploymentXMLFile.getAbsolutePath() + "\""); BufferedWriter bw = new BufferedWriter(new FileWriter(deploymentXMLFile)); for (String line : defaultDeploymentXML) { bw.write(line); bw.newLine(); } bw.flush(); bw.close(); return deploymentXMLFile.getAbsolutePath(); }
33. MethodInterceptorTest#nullMethodInterceptorWorksInTestngXml()
Project: testng
File: MethodInterceptorTest.java
File: MethodInterceptorTest.java
@Test public void nullMethodInterceptorWorksInTestngXml() throws IOException, ParserConfigurationException, SAXException { File f = File.createTempFile("testng-tests-", ""); f.deleteOnExit(); BufferedWriter bw = new BufferedWriter(new FileWriter(f)); bw.write(XML); bw.close(); try { List<XmlSuite> xmlSuites = new Parser(f.getAbsolutePath()).parseToList(); TestNG tng = create(); tng.setXmlSuites(xmlSuites); testNullInterceptor(tng); } catch (Exception ex) { ex.printStackTrace(); } }
34. PostgreSQLUtils#writePasswordFile()
Project: sqoop
File: PostgreSQLUtils.java
File: PostgreSQLUtils.java
/** Write the user's password to a file that is chmod 0600. @return the filename. */ public static String writePasswordFile(String tmpDir, String password) throws IOException { File tempFile = File.createTempFile("pgpass", ".pgpass", new File(tmpDir)); LOG.debug("Writing password to tempfile: " + tempFile); // Make sure it's only readable by the current user. DirectImportUtils.setFilePermissions(tempFile, "0600"); // Actually write the password data into the file. BufferedWriter w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile))); w.write("*:*:*:*:" + password); w.close(); return tempFile.toString(); }
35. FileStreamsTextFileWriterTest#createTempFile()
Project: quarks
File: FileStreamsTextFileWriterTest.java
File: FileStreamsTextFileWriterTest.java
public static Path createTempFile(String name, String extension, String[] lines) throws Exception { Path tmpFile = Files.createTempFile(name, extension); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tmpFile.toFile()), StandardCharsets.UTF_8)); for (int i = 0; i < lines.length; i++) { bw.write(lines[i]); bw.write("\n"); } bw.flush(); bw.close(); return tmpFile; }
36. FileStreamsTest#createTempFile()
Project: quarks
File: FileStreamsTest.java
File: FileStreamsTest.java
public static Path createTempFile(String name, String extension, String[] lines) throws Exception { Path tmpFile = Files.createTempFile(name, extension); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tmpFile.toFile()), StandardCharsets.UTF_8)); for (int i = 0; i < lines.length; i++) { bw.write(lines[i]); bw.write("\n"); } bw.flush(); bw.close(); return tmpFile; }
37. AbstractBaseAdminCommand#sendPostRequest()
Project: pinot
File: AbstractBaseAdminCommand.java
File: AbstractBaseAdminCommand.java
public static String sendPostRequest(String urlString, String payload) throws UnsupportedEncodingException, IOException, JSONException { final URL url = new URL(urlString); final URLConnection conn = url.openConnection(); conn.setDoOutput(true); final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8")); writer.write(payload, 0, payload.length()); writer.flush(); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); final StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } return sb.toString(); }
38. ControllerTest#sendPostRequest()
Project: pinot
File: ControllerTest.java
File: ControllerTest.java
public static String sendPostRequest(String urlString, String payload) throws UnsupportedEncodingException, IOException, JSONException { LOGGER.info("Sending POST to " + urlString + " with payload " + payload); final long start = System.currentTimeMillis(); final URL url = new URL(urlString); final URLConnection conn = url.openConnection(); conn.setDoOutput(true); final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8")); writer.write(payload, 0, payload.length()); writer.flush(); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); final StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } final long stop = System.currentTimeMillis(); LOGGER.info(" Time take for Request : " + payload + " in ms:" + (stop - start)); return sb.toString(); }
39. ControllerTest#sendPutRequest()
Project: pinot
File: ControllerTest.java
File: ControllerTest.java
public static String sendPutRequest(String urlString, String payload) throws IOException { LOGGER.info("Sending PUT to " + urlString + " with payload " + payload); final long start = System.currentTimeMillis(); final URL url = new URL(urlString); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("PUT"); final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8")); writer.write(payload, 0, payload.length()); writer.flush(); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); final StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } final long stop = System.currentTimeMillis(); LOGGER.info(" Time take for Request : " + urlString + " in ms:" + (stop - start)); return sb.toString(); }
40. StreamLinesTest#generateTempFileWithLines()
Project: openjdk
File: StreamLinesTest.java
File: StreamLinesTest.java
static Path generateTempFileWithLines(IntFunction<String> lineGenerator, IntFunction<LineSeparator> lineSeparatorGenerator, int lines, Charset cs, boolean endLineSep) throws IOException { Path p = Files.createTempFile("lines", null); BufferedWriter bw = Files.newBufferedWriter(p, cs); for (int i = 0; i < lines - 1; i++) { bw.write(lineGenerator.apply(i)); bw.write(lineSeparatorGenerator.apply(i).value); } if (lines > 0) { bw.write(lineGenerator.apply(lines - 1)); if (endLineSep) bw.write(lineSeparatorGenerator.apply(lines - 1).value); } bw.flush(); bw.close(); p.toFile().deleteOnExit(); return p; }
41. DropboxSynchronizer#putRemoteFile()
Project: mobileorg-android
File: DropboxSynchronizer.java
File: DropboxSynchronizer.java
public void putRemoteFile(String filename, String contents) throws IOException { FileUtils orgFile = new FileUtils(filename, context); BufferedWriter writer = orgFile.getWriter(); writer.write(contents); writer.close(); File uploadFile = orgFile.getFile(); FileInputStream fis = new FileInputStream(uploadFile); try { this.dropboxApi.putFileOverwrite(this.remotePath + filename, fis, uploadFile.length(), null); } catch (DropboxUnlinkedException e) { throw new IOException("Dropbox Authentication Failed, re-run setup wizard"); } catch (DropboxException e) { throw new IOException("Uploading " + filename + " because: " + e.toString()); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { } } } }
42. SchemaSamplerTest#testFileSampler()
Project: log-synth
File: SchemaSamplerTest.java
File: SchemaSamplerTest.java
@Test public void testFileSampler() throws IOException { File f = new File("numbers.tsv"); f.deleteOnExit(); BufferedWriter out = Files.newBufferedWriter(f.toPath(), Charsets.UTF_8); out.write("a\tb\n"); for (int i = 0; i < 20; i++) { out.write(i + "\t" + (i * i) + "\n"); } out.close(); SchemaSampler s = new SchemaSampler(Resources.asCharSource(Resources.getResource("schema008.json"), Charsets.UTF_8).read()); for (int k = 0; k < 1000; k++) { JsonNode r = s.sample(); assertEquals(6, r.get("x").get("x").asInt() + r.get("x").get("y").asInt()); int i = r.get("y").get("a").asInt(); assertEquals(i * i, r.get("y").get("b").asInt()); } }
43. FileIO#writeVector()
Project: librec
File: FileIO.java
File: FileIO.java
public static <T> void writeVector(String filePath, List<T> ts, Converter<T, String> wh, boolean append) throws Exception { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath, append), "UTF-8")); int i = 0; StringBuilder sb = new StringBuilder(); for (T t : ts) { sb.append(wh.transform(t)); if (++i < ts.size()) sb.append(", "); } bw.write(sb.toString() + "\n"); bw.close(); }
44. ListMessageBodyProvider#writeTo()
Project: Kundera
File: ListMessageBodyProvider.java
File: ListMessageBodyProvider.java
@Override public void writeTo(ArrayList<Object> paramT, Class<?> paramClass, Type paramType, Annotation[] paramArrayOfAnnotation, MediaType paramMediaType, MultivaluedMap<String, Object> paramMultivaluedMap, OutputStream paramOutputStream) throws IOException, WebApplicationException { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(paramOutputStream)); String ts = null; Iterator<Object> i = paramT.iterator(); while (i.hasNext()) { ts += i.next().toString(); } bw.write(ts); bw.flush(); }
45. TestInputFormatValueReader#setup()
Project: kite
File: TestInputFormatValueReader.java
File: TestInputFormatValueReader.java
@BeforeClass public static void setup() throws IOException { localfs = LocalFileSystem.getInstance(); BufferedWriter writer = Files.newWriter(new File(userFile.toString()), Charset.forName("UTF-8")); for (String line : lines) { writer.write(line); writer.newLine(); } writer.flush(); writer.close(); }
46. TestInputFormatKeyReader#setup()
Project: kite
File: TestInputFormatKeyReader.java
File: TestInputFormatKeyReader.java
@BeforeClass public static void setup() throws IOException { localfs = LocalFileSystem.getInstance(); BufferedWriter writer = Files.newWriter(new File(userFile.toString()), Charset.forName("UTF-8")); for (String line : lines) { writer.write(line); writer.newLine(); } writer.flush(); writer.close(); }
47. StripProperties#storeProperties()
Project: jdk7u-jdk
File: StripProperties.java
File: StripProperties.java
private static void storeProperties(Properties properties, OutputStream out) throws IOException { BufferedWriter awriter; awriter = new BufferedWriter(new OutputStreamWriter(out, "8859_1")); for (Enumeration e = properties.keys(); e.hasMoreElements(); ) { String key = (String) e.nextElement(); String val = (String) properties.get(key); key = saveConvert(key, true); val = saveConvert(val, false); writeln(awriter, key + "=" + val); } awriter.flush(); }
48. ScalingTest#generateFrameMTD()
Project: incubator-systemml
File: ScalingTest.java
File: ScalingTest.java
private void generateFrameMTD(String datafile) throws IllegalArgumentException, IOException, Exception { JSONObject mtd = new JSONObject(); mtd.put("data_type", "frame"); mtd.put("format", "csv"); mtd.put("header", false); FileSystem fs = FileSystem.get(TestUtils.conf); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fs.create(new Path(datafile + ".mtd"), true))); out.write(mtd.toString()); out.close(); }
49. MapReduceTool#writeDimsFile()
Project: incubator-systemml
File: MapReduceTool.java
File: MapReduceTool.java
public static void writeDimsFile(String filename, byte[] unknownFlags, long[] maxRows, long[] maxCols) throws IOException { BufferedWriter br = setupOutputFile(filename); StringBuilder line = new StringBuilder(); for (int i = 0; i < unknownFlags.length; i++) { if (unknownFlags[i] != (byte) 0) { line.append(i); line.append(" " + maxRows[i]); line.append(" " + maxCols[i]); line.append("\n"); } } br.write(line.toString()); br.close(); }
50. FileStreamsTextFileWriterTest#createTempFile()
Project: incubator-quarks
File: FileStreamsTextFileWriterTest.java
File: FileStreamsTextFileWriterTest.java
public static Path createTempFile(String name, String extension, String[] lines) throws Exception { Path tmpFile = Files.createTempFile(name, extension); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tmpFile.toFile()), StandardCharsets.UTF_8)); for (int i = 0; i < lines.length; i++) { bw.write(lines[i]); bw.write("\n"); } bw.flush(); bw.close(); return tmpFile; }
51. FileStreamsTest#createTempFile()
Project: incubator-quarks
File: FileStreamsTest.java
File: FileStreamsTest.java
public static Path createTempFile(String name, String extension, String[] lines) throws Exception { Path tmpFile = Files.createTempFile(name, extension); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tmpFile.toFile()), StandardCharsets.UTF_8)); for (int i = 0; i < lines.length; i++) { bw.write(lines[i]); bw.write("\n"); } bw.flush(); bw.close(); return tmpFile; }
52. JavaSimpleCompiler#compile()
Project: hydra
File: JavaSimpleCompiler.java
File: JavaSimpleCompiler.java
public boolean compile(String className, String body) throws IOException { File sourceFile = new File("/tmp/" + className + ".java"); BufferedWriter out = new BufferedWriter(new FileWriter(sourceFile)); out.write(body); out.close(); List<String> optionList = new ArrayList<>(); String classpath = System.getProperty("java.class.path"); log.info("Classpath is " + classpath); optionList.addAll(Arrays.asList("-cp", classpath, "-encoding", "UTF-8")); Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(sourceFile); boolean success = compiler.getTask(null, fileManager, diagnostics, optionList, null, compilationUnits).call(); return success; }
53. DirectPostgresqlManager#writePasswordFile()
Project: hadoop-mapreduce
File: DirectPostgresqlManager.java
File: DirectPostgresqlManager.java
/** Write the user's password to a file that is chmod 0600. @return the filename. */ private String writePasswordFile(String password) throws IOException { String tmpDir = options.getTempDir(); File tempFile = File.createTempFile("pgpass", ".pgpass", new File(tmpDir)); LOG.debug("Writing password to tempfile: " + tempFile); // Make sure it's only readable by the current user. DirectImportUtils.setFilePermissions(tempFile, "0600"); // Actually write the password data into the file. BufferedWriter w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile))); w.write("*:*:*:*:" + password); w.close(); return tempFile.toString(); }
54. DefaultStepDefinitions#I_have_a_patch_file()
Project: geogig
File: DefaultStepDefinitions.java
File: DefaultStepDefinitions.java
@Given("^I have a patch file$") public void I_have_a_patch_file() throws Throwable { Patch patch = new Patch(); String path = NodeRef.appendChild(pointsName, points1.getIdentifier().getID()); Map<PropertyDescriptor, AttributeDiff> map = Maps.newHashMap(); Optional<?> oldValue = Optional.fromNullable(points1.getProperty("sp").getValue()); GenericAttributeDiffImpl diff = new GenericAttributeDiffImpl(oldValue, Optional.of("new")); map.put(pointsType.getDescriptor("sp"), diff); FeatureDiff feaureDiff = new FeatureDiff(path, map, RevFeatureTypeImpl.build(pointsType), RevFeatureTypeImpl.build(pointsType)); patch.addModifiedFeature(feaureDiff); File file = new File(platform.pwd(), "test.patch"); BufferedWriter writer = Files.newWriter(file, Charsets.UTF_8); PatchSerializer.write(writer, patch); writer.flush(); writer.close(); }
55. Caller#openPostConnection()
Project: frostwire-android
File: Caller.java
File: Caller.java
/** * @param method * @param params * @return * @throws IOException */ private HttpURLConnection openPostConnection(final String method, final Map<String, String> params) throws IOException { final HttpURLConnection urlConnection = openConnection(apiRootUrl); urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(true); urlConnection.setUseCaches(true); final OutputStream outputStream = urlConnection.getOutputStream(); final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream)); final String post = buildPostBody(method, params); writer.write(post); writer.close(); return urlConnection; }
56. SimpleFieldSet#writeTo()
Project: fred
File: SimpleFieldSet.java
File: SimpleFieldSet.java
/** Write to the given OutputStream and flush it. */ public void writeTo(OutputStream os, int bufferSize) throws IOException { BufferedOutputStream bos = null; OutputStreamWriter osw = null; BufferedWriter bw = null; bos = new BufferedOutputStream(os, bufferSize); try { osw = new OutputStreamWriter(bos, "UTF-8"); } catch (UnsupportedEncodingException e) { Logger.error(SimpleFieldSet.class, "Impossible: " + e, e); throw e; } bw = new BufferedWriter(osw); writeTo(bw); bw.flush(); }
57. WordSimilarity#calSimilarity()
Project: fnlp
File: WordSimilarity.java
File: WordSimilarity.java
@SuppressWarnings("unchecked") public void calSimilarity(String outpath) throws Exception { BufferedWriter bout = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outpath), "UTF-8")); for (int i = 0; i < hashlist.size(); i++) bout.write("\t" + word.get(i)); bout.write("\n"); for (int i = 0; i < hashlist.size(); i++) { bout.write(word.get(i) + "\t"); for (int j = 0; j < hashlist.size(); j++) { float f = is.calc((THashSet<String>) hashlist.get(i), (THashSet<String>) hashlist.get(j)); f = (float) (Math.round(f * 1000)) / 1000; bout.write(f + "\t"); } bout.write("\n"); } bout.close(); }
58. TestFlumeShell#testLoadConfigCommand()
Project: flume
File: TestFlumeShell.java
File: TestFlumeShell.java
/** * Create a master, create a config file, connect via shell, load config file, * compare if flow looks as expected in FlumeConfigData. */ @Test public void testLoadConfigCommand() throws IOException { FlumeShell sh = new FlumeShell(); long retval; retval = sh.executeLine("connect localhost:" + FlumeConfiguration.DEFAULT_ADMIN_PORT); assertEquals(0, retval); File saveFile = FileUtil.createTempFile("test-flume", ""); saveFile.deleteOnExit(); BufferedWriter out = new BufferedWriter(new FileWriter(saveFile)); out.write("foo : null | console;\n"); out.close(); retval = sh.executeLine("exec load '" + saveFile.getAbsolutePath() + "'"); assertEquals(0, retval); ConfigurationManager manager = flumeMaster.getSpecMan(); FlumeConfigData data = manager.getConfig("foo"); assertEquals(data.getSinkConfig(), "console"); assertEquals(data.getSourceConfig(), "null"); }
59. TestExecNioSource#testRestart()
Project: flume
File: TestExecNioSource.java
File: TestExecNioSource.java
/** * Test that restarting an exec after a pause works correctly. Requires * GNU-compatible 'date' to work correctly. */ @Test public void testRestart() throws IOException, InterruptedException { File temp = FileUtil.createTempFile("flmtst", null); temp.deleteOnExit(); BufferedWriter out = new BufferedWriter(new FileWriter(temp)); out.write("#!/bin/bash\n date +%s"); out.close(); String cmd = temp.getAbsolutePath(); ExecNioSource.Builder builder = new ExecNioSource.Builder(); // aggregate = false, restart=true, restart after 1000ms EventSource source = builder.build("/bin/bash " + cmd, "false", "true", "1000"); source.open(); Event e1 = source.next(); Event e2 = source.next(); source.close(); String t1 = new String(e1.getBody()); String t2 = new String(e2.getBody()); long time1 = Long.parseLong(t1); long time2 = Long.parseLong(t2); assertTrue("Time difference with repeated exec should be >= 1s", time2 - time1 >= 1); }
60. TestExecNioSource#testAggregate()
Project: flume
File: TestExecNioSource.java
File: TestExecNioSource.java
/** * Test that aggregation works correctly - wait until file handle is closed * before returning the entire output * * @throws InterruptedException */ @Test public void testAggregate() throws IOException, InterruptedException { File temp = FileUtil.createTempFile("flmtst", null); temp.deleteOnExit(); BufferedWriter out = new BufferedWriter(new FileWriter(temp)); out.write("#!/bin/bash\n echo \"Hello\"\necho \"World!\"\n"); out.close(); String cmd = temp.getAbsolutePath(); ExecNioSource.Builder builder = new ExecNioSource.Builder(); EventSource source = builder.build("/bin/bash " + cmd, "true"); source.open(); // need to sleep to let things percolate through threads. Clock.sleep(250); Event e = source.next(); source.close(); String output = new String(e.getBody()); assertEquals("Expected aggregate exec output to be 'Hello\nWorld!', " + "but got '" + output + "'", output, "Hello\nWorld!\n"); }
61. TestExecNioSource#testReadStdErr()
Project: flume
File: TestExecNioSource.java
File: TestExecNioSource.java
/** * Test that we get some output from stderr * * @throws InterruptedException */ @Test public void testReadStdErr() throws IOException, InterruptedException { File temp = FileUtil.createTempFile("flmtst", null); temp.deleteOnExit(); BufferedWriter out = new BufferedWriter(new FileWriter(temp)); out.write("#!/bin/bash\necho \"Hello world!\" >&2 \n"); out.close(); String cmd = temp.getAbsolutePath(); EventSource source = new ExecNioSource.Builder().build("/bin/bash " + cmd); source.open(); Event e = source.next(); String body = new String(e.getBody()); String src = new String(e.get(ExecNioSource.A_PROC_SOURCE)); source.close(); assertEquals("Expected event body to be 'Hello World!', but got '" + body + "'", body, "Hello world!"); assertEquals("Expected to receive event from STDERR, but got " + src, src, "STDERR"); }
62. TestExecNioSource#testAggModeMultiWrite()
Project: flume
File: TestExecNioSource.java
File: TestExecNioSource.java
/** * Test that an event that gets written slowly gets fully read. * * @throws FlumeSpecException * @throws IOException * @throws InterruptedException */ @Test public void testAggModeMultiWrite() throws IOException, FlumeSpecException, InterruptedException { File temp = FileUtil.createTempFile("slowwrite", ".sh"); temp.deleteOnExit(); BufferedWriter out = new BufferedWriter(new FileWriter(temp)); // echo, sleep 1s, echo out.write("#!/bin/bash\necho \"Hello world!\" >&2 \n" + "sleep 1s \necho \"Hello world!\" >&2 \n"); out.close(); String cmd = temp.getAbsolutePath(); EventSource source = new ExecNioSource.Builder().build("/bin/bash " + cmd, "true"); source.open(); Event e = source.next(); assertNotNull(e); // check that we read both lines assertEquals(26, e.getBody().length); source.close(); // Check that the stdout reader closed correctly assertTrue(((ExecNioSource) source).readOut.signalDone.get()); }
63. CodeDictionary#write()
Project: Cubert
File: CodeDictionary.java
File: CodeDictionary.java
public void write(FileSystem fs, Path path) throws IOException { // if the path exists, rename the existing file with ".old" suffix if (fs.exists(path)) { Path renamePath = new Path(path.toString() + ".old"); fs.delete(renamePath, false); fs.rename(path, renamePath); } // Write data to file FSDataOutputStream ostream = fs.create(path); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(ostream)); for (Map.Entry<String, Integer> entry : keyToCodeMap.entrySet()) { String line = String.format("%s %d\n", entry.getKey(), entry.getValue()); writer.write(line); } writer.flush(); writer.close(); ostream.close(); }
64. DumpMatrices#dumpMatrix()
Project: CoreNLP
File: DumpMatrices.java
File: DumpMatrices.java
public static void dumpMatrix(String filename, SimpleMatrix matrix) throws IOException { String matrixString = matrix.toString(); int newLine = matrixString.indexOf("\n"); if (newLine >= 0) { matrixString = matrixString.substring(newLine + 1); } FileWriter fout = new FileWriter(filename); BufferedWriter bout = new BufferedWriter(fout); bout.write(matrixString); bout.close(); fout.close(); }
65. DcorefExactOutputITest#saveResults()
Project: CoreNLP
File: DcorefExactOutputITest.java
File: DcorefExactOutputITest.java
public static void saveResults(String filename, Map<Integer, CorefChain> chains) throws IOException { FileWriter fout = new FileWriter(filename); BufferedWriter bout = new BufferedWriter(fout); List<Integer> keys = new ArrayList<Integer>(chains.keySet()); Collections.sort(keys); for (Integer key : keys) { saveKey(bout, key, chains.get(key)); } bout.flush(); bout.close(); fout.close(); }
66. FileConsumptionTest#safelyWriteFile()
Project: camel-cookbook-examples
File: FileConsumptionTest.java
File: FileConsumptionTest.java
private void safelyWriteFile(String fileName, String text) throws IOException { File outputFile = new File(TARGET_TEMP + fileName); log.info("Writing temporary file: {}", outputFile.getAbsolutePath()); BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile)); writer.append(text); writer.close(); // move the file - the Camel file consumer doesn't like files being written at the same time File destination = new File(TARGET_IN + fileName); log.info("Moving temporary file to: {}", destination.getAbsolutePath()); outputFile.renameTo(destination); }
67. TestBoneCPConfig#testLoadPropertyFileInvalid()
Project: bonecp
File: TestBoneCPConfig.java
File: TestBoneCPConfig.java
/** * Tries to load an invalid property file. * @throws CloneNotSupportedException * @throws IOException */ @Test public void testLoadPropertyFileInvalid() throws CloneNotSupportedException, IOException { BoneCPConfig config = new BoneCPConfig(); BoneCPConfig clone = config.clone(); File f = File.createTempFile("bonecp-test", ".xml"); BufferedWriter bw = new BufferedWriter(new FileWriter(f)); bw.write("This file is meant to test invalid xml file parsing."); config.setConfigFile(f.getAbsolutePath()); // config.loadProperties(); // "invalid-property-file.xml"); // calls loadProperties eventually config.sanitize(); bw.close(); f.delete(); assertTrue(config.hasSameConfiguration(clone)); }
68. FTPBlobUploadStrategyTest#testWriteDenied()
Project: activemq-artemis
File: FTPBlobUploadStrategyTest.java
File: FTPBlobUploadStrategyTest.java
public void testWriteDenied() throws Exception { userNamePass = "guest"; setConnection(); File file = File.createTempFile("amq-data-file-", ".dat"); // lets write some data BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.append("hello world"); writer.close(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); ((ActiveMQConnection) connection).setCopyMessageOnSend(false); ActiveMQBlobMessage message = (ActiveMQBlobMessage) ((ActiveMQSession) session).createBlobMessage(file); message.setJMSMessageID("testmessage"); try { message.onSend(); } catch (JMSException e) { e.printStackTrace(); return; } fail("Should have failed with permission denied exception!"); }
69. FTPBlobUploadStrategyTest#testFileUpload()
Project: activemq-artemis
File: FTPBlobUploadStrategyTest.java
File: FTPBlobUploadStrategyTest.java
public void testFileUpload() throws Exception { setConnection(); File file = File.createTempFile("amq-data-file-", ".dat"); // lets write some data BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.append("hello world"); writer.close(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); ((ActiveMQConnection) connection).setCopyMessageOnSend(false); ActiveMQBlobMessage message = (ActiveMQBlobMessage) ((ActiveMQSession) session).createBlobMessage(file); message.setJMSMessageID("testmessage"); message.onSend(); assertEquals(ftpUrl + "ID_testmessage", message.getURL().toString()); File uploaded = new File(ftpHomeDirFile, "ID_testmessage"); assertTrue("File doesn't exists", uploaded.exists()); }
70. FileIO#writeList()
Project: librec
File: FileIO.java
File: FileIO.java
public static <T> void writeList(String filePath, Collection<T> ts, Converter<T, String> lw, boolean append) throws Exception { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath, append), "UTF-8")); StringBuilder contents = new StringBuilder(); int count = 0; for (T t : ts) { contents.append(lw != null ? lw.transform(t) : t); contents.append("\n"); count++; if (count >= 1000) { bw.write(contents.toString()); count = 0; contents = new StringBuilder(); } } if (contents.capacity() > 0) bw.write(contents.toString()); bw.close(); }
71. MimeHeader#writeTo()
Project: k-9
File: MimeHeader.java
File: MimeHeader.java
public void writeTo(OutputStream out) throws IOException { BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out), 1024); for (Field field : mFields) { if (field.hasRawData()) { writer.write(field.getRaw()); } else { writeNameValueField(writer, field); } writer.write("\r\n"); } writer.flush(); }
72. TextfileChangesProvider#save()
Project: jdeb
File: TextfileChangesProvider.java
File: TextfileChangesProvider.java
public void save(OutputStream pOutput) throws IOException { BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(pOutput)); for (ChangeSet changeSet : changeSets) { writer.write("release "); writer.write("date=" + fmt.format(changeSet.getDate()) + ","); writer.write("version=" + changeSet.getVersion() + ","); writer.write("urgency=" + changeSet.getUrgency() + ","); writer.write("by=" + changeSet.getChangedBy() + ","); writer.write("distribution=" + changeSet.getDistribution()); writer.write("\n"); for (String change : changeSet.getChanges()) { writer.write(" * "); writer.write(change); writer.write("\n"); } } writer.close(); }
73. DataStoreTextWriter#writeToFile()
Project: jackrabbit-oak
File: DataStoreTextWriter.java
File: DataStoreTextWriter.java
private void writeToFile(String fileName, Set<String> blobIds) throws IOException { if (blobIds.isEmpty()) { return; } File file = new File(directory, fileName); BufferedWriter bw = Files.newWriter(file, Charsets.UTF_8); for (String id : blobIds) { bw.write(id); bw.newLine(); } bw.close(); }
74. URIListHandler#writeTo()
Project: incubator-taverna-server
File: URIListHandler.java
File: URIListHandler.java
@Override public void writeTo(List<URI> list, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException { String encoding = mediaType.getParameters().get("encoding"); if (encoding == null) { encoding = PREFERRED_ENCODING; httpHeaders.putSingle("Content-Type", URI_LIST + ";encoding=" + encoding); } BufferedWriter w = new BufferedWriter(new OutputStreamWriter(entityStream, encoding)); for (URI uri : list) { w.write(uri.toString()); w.newLine(); } w.flush(); }
75. TestPhrase#testExtract()
Project: HanLP
File: TestPhrase.java
File: TestPhrase.java
public void testExtract() throws Exception { List<File> fileList = FolderWalker.open(FOLDER); Map<String, String> phraseMap = new TreeMap<String, String>(); int i = 0; for (File file : fileList) { System.out.print(++i + " / " + fileList.size() + " " + file.getName() + " "); String path = file.getAbsolutePath(); List<String> phraseList = MutualInformationEntropyPhraseExtractor.extract(IOUtil.readTxt(path), 3); System.out.print(phraseList); for (String phrase : phraseList) { phraseMap.put(phrase, file.getAbsolutePath()); } System.out.println(); } BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("data/phrase.txt"))); for (Map.Entry<String, String> entry : phraseMap.entrySet()) { bw.write(entry.getKey() + "\t" + entry.getValue()); bw.newLine(); } bw.close(); }
76. TestConfiguration#testIncludes()
Project: hadoop-common
File: TestConfiguration.java
File: TestConfiguration.java
public void testIncludes() throws Exception { tearDown(); System.out.println("XXX testIncludes"); out = new BufferedWriter(new FileWriter(CONFIG2)); startConfig(); appendProperty("a", "b"); appendProperty("c", "d"); endConfig(); out = new BufferedWriter(new FileWriter(CONFIG)); startConfig(); addInclude(CONFIG2); appendProperty("e", "f"); appendProperty("g", "h"); endConfig(); // verify that the includes file contains all properties Path fileResource = new Path(CONFIG); conf.addResource(fileResource); assertEquals(conf.get("a"), "b"); assertEquals(conf.get("c"), "d"); assertEquals(conf.get("e"), "f"); assertEquals(conf.get("g"), "h"); tearDown(); }
77. TestLocalRunner#createInputFile()
Project: hadoop-20
File: TestLocalRunner.java
File: TestLocalRunner.java
/** * Create a single input file in the input directory. * @param dirPath the directory in which the file resides * @param id the file id number * @param numRecords how many records to write to each file. */ private void createInputFile(Path dirPath, int id, int numRecords) throws IOException { final String MESSAGE = "This is a line in a file: "; Path filePath = new Path(dirPath, "" + id); Configuration conf = new Configuration(); FileSystem fs = FileSystem.getLocal(conf); OutputStream os = fs.create(filePath); BufferedWriter w = new BufferedWriter(new OutputStreamWriter(os)); for (int i = 0; i < numRecords; i++) { w.write(MESSAGE + id + " " + i + "\n"); } w.close(); }
78. SQLServerDatatypeExportDelimitedFileManualTest#createFile()
Project: sqoop
File: SQLServerDatatypeExportDelimitedFileManualTest.java
File: SQLServerDatatypeExportDelimitedFileManualTest.java
public void createFile(DATATYPES dt, String[] data) throws IOException { Path tablePath = getTablePath(dt); Path filePath = new Path(tablePath, "part0000"); Configuration conf = new Configuration(); String hdfsroot; hdfsroot = System.getProperty("ms.datatype.test.hdfsprefix"); if (hdfsroot == null) { hdfsroot = "hdfs://localhost/"; } conf.set("fs.default.name", hdfsroot); FileSystem fs = FileSystem.get(conf); fs.mkdirs(tablePath); System.out.println("-----------------------------------Path : " + filePath); OutputStream os = fs.create(filePath); BufferedWriter w = new BufferedWriter(new OutputStreamWriter(os)); for (int i = 0; i < data.length; i++) { w.write(data[i] + "\n"); } w.close(); os.close(); }
79. NetezzaExportManualTest#createExportFile()
Project: sqoop
File: NetezzaExportManualTest.java
File: NetezzaExportManualTest.java
protected void createExportFile(ColumnGenerator... extraCols) throws IOException { String ext = ".txt"; Path tablePath = getTablePath(); Path filePath = new Path(tablePath, "part0" + ext); Configuration conf = new Configuration(); if (!BaseSqoopTestCase.isOnPhysicalCluster()) { conf.set(CommonArgs.FS_DEFAULT_NAME, CommonArgs.LOCAL_FS); } FileSystem fs = FileSystem.get(conf); fs.mkdirs(tablePath); OutputStream os = fs.create(filePath); BufferedWriter w = new BufferedWriter(new OutputStreamWriter(os)); for (int i = 0; i < 3; i++) { String line = getRecordLine(i, extraCols); w.write(line); LOG.debug("Create Export file - Writing line : " + line); } w.close(); os.close(); }
80. ListWriter#write()
Project: spacewalk
File: ListWriter.java
File: ListWriter.java
/** * * {@inheritDoc} */ public void write(List<Handler> handlers, Map<String, String> serializers) throws Exception { FileWriter fstream = new FileWriter(LIST_OUT); BufferedWriter out = new BufferedWriter(fstream); for (Handler handler : handlers) { for (ApiCall call : handler.getCalls()) { out.write(handler.getName() + "." + call.getName() + " " + call.getMethod().parameters().length + " "); for (Parameter param : call.getMethod().parameters()) { out.write(param.type().typeName() + " "); } out.write("\n"); } } out.close(); }
81. SessionIDAnalysis#exportIDSToCSV()
Project: OWASP-WebScarab
File: SessionIDAnalysis.java
File: SessionIDAnalysis.java
public void exportIDSToCSV(String key, File file) throws IOException { int count = _model.getSessionIDCount(key); if (count == 0) return; BufferedWriter bw = new BufferedWriter(new FileWriter(file)); StringBuffer buff = new StringBuffer(); for (int i = 0; i < count; i++) { SessionID id = _model.getSessionIDAt(key, i); buff.append(id.getDate().getTime()); buff.append(",").append(_model.getSessionIDValue(key, id)); buff.append(",").append(id.getValue()).append("\n"); bw.write(buff.toString().toCharArray()); buff.delete(0, buff.length()); } bw.close(); }
82. DatabaseFieldConfigLoaderTest#testLocalEnumClass()
Project: ormlite-core
File: DatabaseFieldConfigLoaderTest.java
File: DatabaseFieldConfigLoaderTest.java
@Test public void testLocalEnumClass() throws Exception { String fieldName = "ourEnum"; Field field = LocalEnumField.class.getDeclaredField(fieldName); String tableName = "foo"; DatabaseFieldConfig config = DatabaseFieldConfig.fromField(databaseType, tableName, field); StringWriter writer = new StringWriter(); BufferedWriter bufferedWriter = new BufferedWriter(writer); DatabaseFieldConfigLoader.write(bufferedWriter, config, tableName); bufferedWriter.flush(); String configString = writer.toString(); System.out.println(configString); DatabaseFieldConfig result = DatabaseFieldConfigLoader.fromReader(new BufferedReader(new StringReader(configString))); assertEquals(fieldName, result.getFieldName()); assertEquals(OurAnonymousEnum.ONE, result.getUnknownEnumValue()); }
83. ODataDebugResponseWrapper#wrapInJson()
Project: olingo-odata2
File: ODataDebugResponseWrapper.java
File: ODataDebugResponseWrapper.java
private InputStream wrapInJson(final List<DebugInfo> parts) throws IOException { CircleStreamBuffer csb = new CircleStreamBuffer(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(csb.getOutputStream(), "UTF-8")); JsonStreamWriter jsonStreamWriter = new JsonStreamWriter(writer); jsonStreamWriter.beginObject().name(parts.get(0).getName().toLowerCase(Locale.ROOT)); parts.get(0).appendJson(jsonStreamWriter); jsonStreamWriter.separator().name(parts.get(1).getName().toLowerCase(Locale.ROOT)); parts.get(1).appendJson(jsonStreamWriter); jsonStreamWriter.separator().name("server").beginObject().namedStringValueRaw("version", ODataDebugResponseWrapper.class.getPackage().getImplementationVersion()); for (final DebugInfo part : parts.subList(2, parts.size())) { jsonStreamWriter.separator().name(part.getName().toLowerCase(Locale.ROOT)); part.appendJson(jsonStreamWriter); } jsonStreamWriter.endObject().endObject(); writer.flush(); csb.closeWrite(); return csb.getInputStream(); }
84. FileUtils#fetch()
Project: mobileorg-android
File: FileUtils.java
File: FileUtils.java
/** * Read everything from the given reader and write to it {@link #fileName} */ public void fetch(BufferedReader reader) throws IOException { BufferedWriter writer = getWriter(); final int BUFFER_SIZE = 23 * 1024; char[] baf = new char[BUFFER_SIZE]; int actual = 0; while (actual != -1) { writer.write(baf, 0, actual); actual = reader.read(baf, 0, BUFFER_SIZE); } writer.close(); }
85. DatasetConverter#convertIrisNormalizedToMetronome()
Project: Metronome
File: DatasetConverter.java
File: DatasetConverter.java
/** * Example: * 0.64556962, 0.795454545, 0.202898551, 0.08, 1, 0, 0 * * 7 columns in dataset * * @param filename * @throws IOException */ public static void convertIrisNormalizedToMetronome(String filename, String file_out) throws IOException { // src/test/resources/data/iris/iris_data_normalised.txt BufferedWriter bw = new BufferedWriter(new FileWriter(file_out)); BufferedReader br = new BufferedReader(new FileReader(filename)); String line; while ((line = br.readLine()) != null) { // process the line. String formatted_line = formatIrisColumnToMetronomeRecord(line); // System.out.println("old > " + line); // System.out.println("new > " + formatted_line); bw.write(formatted_line); } br.close(); bw.close(); }
86. NIST_HandWritingDatasetUtils#convertIrisNormalizedToMetronome()
Project: Metronome
File: NIST_HandWritingDatasetUtils.java
File: NIST_HandWritingDatasetUtils.java
/** * Example: * 0.64556962, 0.795454545, 0.202898551, 0.08, 1, 0, 0 * * 7 columns in dataset * * @param filename * @throws IOException */ public static void convertIrisNormalizedToMetronome(String filename, String file_out) throws IOException { // src/test/resources/data/iris/iris_data_normalised.txt BufferedWriter bw = new BufferedWriter(new FileWriter(file_out)); BufferedReader br = new BufferedReader(new FileReader(filename)); String line; while ((line = br.readLine()) != null) { // process the line. String formatted_line = formatNISTHandwritingColumnToMetronomeRecord(line, 16); System.out.println("old > " + line); System.out.println("new > " + formatted_line); bw.write(formatted_line); } br.close(); bw.close(); System.out.println("done..."); }
87. LensesDatasetUtils#convertLensesNormalizedToMetronome()
Project: Metronome
File: LensesDatasetUtils.java
File: LensesDatasetUtils.java
/** * Example: * * @param filename * @throws Exception */ public static void convertLensesNormalizedToMetronome(String filename, String file_out) throws Exception { // src/test/resources/data/iris/iris_data_normalised.txt BufferedWriter bw = new BufferedWriter(new FileWriter(file_out)); BufferedReader br = new BufferedReader(new FileReader(filename)); String line; while ((line = br.readLine()) != null) { // process the line. String formatted_line = formatToMetronomeRecord(line, 3); // System.out.println("old > " + line); // System.out.println("new > " + formatted_line); bw.write(formatted_line); } br.close(); bw.close(); }
88. BreastCancerWisconsin_DatasetUtils#convertBCWNormalizedToMetronome()
Project: Metronome
File: BreastCancerWisconsin_DatasetUtils.java
File: BreastCancerWisconsin_DatasetUtils.java
/** * Example: * 0.64556962, 0.795454545, 0.202898551, 0.08, 1, 0, 0 * * 7 columns in dataset * * @param filename * @throws Exception */ public static void convertBCWNormalizedToMetronome(String filename, String file_out) throws Exception { // src/test/resources/data/iris/iris_data_normalised.txt BufferedWriter bw = new BufferedWriter(new FileWriter(file_out)); BufferedReader br = new BufferedReader(new FileReader(filename)); String line; while ((line = br.readLine()) != null) { // process the line. String formatted_line = formatIrisColumnToMetronomeRecord(line, 10); // System.out.println("old > " + line); // System.out.println("new > " + formatted_line); bw.write(formatted_line); } br.close(); bw.close(); }
89. StanfordParser#main()
Project: lucida
File: StanfordParser.java
File: StanfordParser.java
// private static void printOffsets(String sentence, Tree tree) // { // if (tree.isLeaf()) return; // MapLabel label = (MapLabel) tree.label(); // int begin = (Integer) label.get(BEGIN_KEY); // int end = (Integer) label.get(END_KEY); // int index = (Integer) label.index(); // String str = null; // if (begin < 0 || begin > sentence.length() || end < begin || end > sentence.length()) { // str = "error"; // } else { // str = sentence.substring(begin, end); // } // System.out.println(label.value()+"("+index+":"+begin+","+end+"): "+str); // for (Tree child : tree.children()) // printOffsets(sentence, child); // } public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("USAGE: StanfordParser <inputSentencesFile>"); System.out.println("Output stored in: <inputSentencesFile>.parses"); System.exit(0); } StanfordParser.initialize(); List<String> sentences = new ArrayList<String>(); BufferedReader in = new BufferedReader(new FileReader(args[0])); BufferedWriter out = new BufferedWriter(new FileWriter(args[0] + ".parses")); String sentence; while ((sentence = in.readLine()) != null) { sentences.add(sentence); } for (String s : sentences) { out.append(StanfordParser.parse(s) + "\n"); } out.close(); in.close(); }
90. TestConfiguration#testIncludes()
Project: hadoop-20
File: TestConfiguration.java
File: TestConfiguration.java
public void testIncludes() throws Exception { tearDown(); System.out.println("XXX testIncludes"); out = new BufferedWriter(new FileWriter(CONFIG2)); startConfig(); appendProperty("a", "b"); appendProperty("c", "d"); endConfig(); out = new BufferedWriter(new FileWriter(CONFIG)); startConfig(); addInclude(CONFIG2); appendProperty("e", "f"); appendProperty("g", "h"); endConfig(); // verify that the includes file contains all properties Path fileResource = new Path(CONFIG); conf.addResource(fileResource); assertEquals(conf.get("a"), "b"); assertEquals(conf.get("c"), "d"); assertEquals(conf.get("e"), "f"); assertEquals(conf.get("g"), "h"); tearDown(); }
91. TestConfiguration#testFinalParam()
Project: hadoop-20
File: TestConfiguration.java
File: TestConfiguration.java
public void testFinalParam() throws IOException { out = new BufferedWriter(new FileWriter(CONFIG)); startConfig(); declareProperty("my.var", "", "", true); endConfig(); Path fileResource = new Path(CONFIG); Configuration conf1 = new Configuration(); conf1.addResource(fileResource); assertNull("my var is not null", conf1.get("my.var")); out = new BufferedWriter(new FileWriter(CONFIG2)); startConfig(); declareProperty("my.var", "myval", "myval", false); endConfig(); fileResource = new Path(CONFIG2); Configuration conf2 = new Configuration(conf1); conf2.addResource(fileResource); assertNull("my var is not final", conf2.get("my.var")); }
92. Environment#writeParameterFile()
Project: gs-core
File: Environment.java
File: Environment.java
/** * Save the curent parameters to a file. * @param fileName Name of the file to save the config in. * @throws IOException For any output error on the given file name. */ public void writeParameterFile(String fileName) throws IOException { BufferedWriter bw = new BufferedWriter(new FileWriter(fileName)); Set<String> ks = parameters.keySet(); for (String key : ks) { bw.write(key + " = " + parameters.get(key)); bw.newLine(); } bw.close(); }
93. DICT#toBMES()
Project: fnlp
File: DICT.java
File: DICT.java
/** * ?????BMES?? * @param file * @throws IOException */ public void toBMES(String file, int duplicateNum) throws IOException { BufferedWriter bout = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), "UTF-8")); for (String line : set) { if (line.length() > 1) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < duplicateNum; i++) { sb.append(line); if (i < duplicateNum - 1) sb.append(" "); } line = sb.toString(); } String s = Tags.genSegSequence(line, "\\s+", 4); bout.write(s); } bout.close(); }
94. MyFiles#conver()
Project: fnlp
File: MyFiles.java
File: MyFiles.java
/** * ?????? * @param infile * @param outfile * @param enc1 * @param enc2 * @throws IOException */ public static void conver(String infile, String outfile, String enc1, String enc2) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(infile), enc1)); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outfile), enc2)); String line = null; while ((line = in.readLine()) != null) { line = line.trim(); if (line.length() == 0) continue; out.write(line); out.newLine(); } in.close(); out.close(); }
95. MyCollection#write()
Project: fnlp
File: MyCollection.java
File: MyCollection.java
/** * ?Map???? * @param map * @throws IOException */ public static void write(Map map, String file) throws IOException { BufferedWriter bout = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8")); Iterator iterator = map.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); String key = entry.getKey().toString(); String v = entry.getValue().toString(); bout.append(key); bout.append("\t"); bout.append(v); bout.newLine(); } bout.close(); }
96. WordSimilarity#dirSougouCAReader()
Project: fnlp
File: WordSimilarity.java
File: WordSimilarity.java
public void dirSougouCAReader(String dirpath, String outpath) throws IOException { File idir = new File(dirpath); File[] files = idir.listFiles(); BufferedWriter bout = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outpath), "UTF-8")); for (File file : files) { String strFilePath = file.getAbsolutePath(); SougouCA sca = new SougouCA(strFilePath); while (sca.hasNext()) { String s = (String) sca.next().getData(); s = tc.normalize(s); if (s.length() == 0) continue; bout.write(s + "\n"); } } bout.close(); System.out.println("Done!"); }
97. SougouCA#main()
Project: fnlp
File: SougouCA.java
File: SougouCA.java
/** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { BufferedWriter bout = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("./tmpdata/trad.txt"), "UTF-8")); SougouCA sca = new SougouCA("./tmpdata/SogouCa/news.allsites.010805.txt"); while (sca.hasNext()) { String s = (String) sca.next().getData(); s = tc.normalize(s); // System.out.println(s); if (s.length() == 0) continue; bout.write(s); bout.write("\n"); } bout.close(); System.out.println("Done!"); }
98. Tags#processFile()
Project: fnlp
File: Tags.java
File: Tags.java
/** * ?????????????? * @param infile * @param outfile * @throws IOException */ public static void processFile(String infile, String outfile, String delimer, int tagnum) throws IOException { BufferedReader in = new BufferedReader(new UnicodeReader(new FileInputStream(infile), "utf8")); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outfile), "utf8")); String line = null; while ((line = in.readLine()) != null) { line = line.trim(); String newline; newline = genSegSequence(line, delimer, tagnum); out.write(newline); // out.newLine(); } in.close(); out.close(); }
99. ChineseTrans#toHalfWidthFile()
Project: fnlp
File: ChineseTrans.java
File: ChineseTrans.java
/** * ???????????? * @param infile * @param outfile * @throws IOException */ public static void toHalfWidthFile(String infile, String outfile) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(infile), "utf8")); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outfile), "utf8")); String line = null; while ((line = in.readLine()) != null) { line = line.trim(); if (line.length() == 0) continue; line = toHalfWidth(line); out.write(line); out.newLine(); } in.close(); out.close(); }
100. CsvDataExporter#exportData()
Project: financius-public
File: CsvDataExporter.java
File: CsvDataExporter.java
@Override public void exportData(OutputStream outputStream) throws Exception { final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream)); final Cursor cursor = Tables.Transactions.getQuery().from(context, TransactionsProvider.uriTransactions()).execute(); try { if (cursor.moveToFirst()) { writeCsv(writer, cursor); } } finally { IOUtils.closeQuietly(cursor); } writer.close(); }