Java Code Examples for java.io.BufferedWriter
The following code examples are extracted from open source projects. You can click to
vote up the examples that are useful to you.
Example 1
From project aws-tasks, under directory /src/main/java/datameer/awstasks/util/.
Source file: IoUtil.java

public static void writeFile(File file,String... lines) throws IOException { BufferedWriter writer=new BufferedWriter(new FileWriter(file)); for ( String line : lines) { writer.write(line); writer.newLine(); } writer.close(); }
Example 2
From project arquillian-rusheye, under directory /rusheye-impl/src/main/java/org/jboss/rusheye/oneoff/.
Source file: XmlWriter.java

private void createHtmlFile(File newDir,ComparisonResult cr) throws IOException { String templateName=cr.isEqualsImages() ? "template_same_images.html" : "template_different_images.html"; BufferedWriter writer=new BufferedWriter(new FileWriter(new File(newDir,"result.html"))); BufferedReader template=new BufferedReader(new FileReader(templateName)); String line; while ((line=template.readLine()) != null) { writer.write(replacePlaceholders(cr,newDir,line)); } template.close(); writer.close(); }
Example 3
From project asadmin, under directory /asadmin-java/src/main/java/org/n0pe/asadmin/commands/.
Source file: CreateFileUser.java

@Override public String handlePasswordFile(String configuredPasswordFile) throws AsAdminException { try { File passwordTempFile=File.createTempFile("asadmin-create-file-user",".pwd"); passwordTempFile.deleteOnExit(); FileUtils.copyFile(new File(configuredPasswordFile),passwordTempFile); BufferedWriter out=new BufferedWriter(new FileWriter(passwordTempFile)); out.write("AS_ADMIN_USERPASSWORD=" + new String(password)); out.close(); return passwordTempFile.getAbsolutePath(); } catch ( IOException ex) { throw new AsAdminException("Unable to handle password file for CreateFileUser command",ex); } }
Example 4
public static void dumpToFile(Dictionary dict,Collection<EquivClassCandRanking> candRankings,String fileName) throws Exception { BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName),DEFAULT_ENCODING)); Set<EquivalenceClass> translations; for ( EquivClassCandRanking candRanking : candRankings) { if (null != (translations=dict.translate(candRanking.m_eq))) { candRanking.flagTranslations(translations); } writer.write(candRanking.toString()); writer.newLine(); } writer.close(); }
Example 5
From project Book-Catalogue, under directory /src/com/eleybourn/bookcatalogue/.
Source file: StorageUtils.java

/** * Check if the sdcard is writable * @return success or failure */ static public boolean sdCardWritable(){ try { BufferedWriter out=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(EXTERNAL_FILE_PATH + "/.nomedia"),UTF8),BUFFER_SIZE); out.write(""); out.close(); return true; } catch ( IOException e) { return false; } }
Example 6
From project 16Blocks, under directory /src/main/java/de/minestar/sixteenblocks/Threads/.
Source file: CheckTicketThread.java

public void saveCheckTickets(){ if (checkedTickets.isEmpty()) return; try { BufferedWriter bWriter=new BufferedWriter(new FileWriter(checkedTicketsFile)); for ( Integer i : checkedTickets) { bWriter.write(i.toString()); bWriter.newLine(); } bWriter.close(); } catch ( Exception e) { ConsoleUtils.printException(e,Core.NAME,"Can't save used ticket names!"); } }
Example 7
From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/generator/model/.
Source file: Model.java

public boolean saveModel(String file) throws IOException { BufferedWriter w=new BufferedWriter(new FileWriter(new File(file))); writeToStream(w); w.flush(); w.close(); return true; }
Example 8
From project AdServing, under directory /modules/utilities/common/src/main/java/net/mad/ads/common/template/impl/freemarker/.
Source file: FMTemplateManager.java

public String processTemplate(String name,Map<String,Object> parameters) throws IOException { try { Template temp=templates.get(name); StringWriter sw=new StringWriter(); BufferedWriter bw=new BufferedWriter(sw); temp.process(parameters,bw); bw.flush(); return sw.toString(); } catch ( Exception e) { throw new IOException(e); } }
Example 9
public void saveXML(String path){ Document doc=new Document(getXML()); XMLOutputter outp=new XMLOutputter(Format.getPrettyFormat()); BufferedWriter outputStream; try { outputStream=new BufferedWriter(new FileWriter(path)); outp.output(doc,outputStream); } catch ( IOException e) { e.printStackTrace(); } }
Example 10
From project anarchyape, under directory /src/main/java/ape/.
Source file: DenialOfServiceRunner.java

public static void sendRawLine(String text,Socket sock){ try { BufferedWriter out=new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())); out.write(text); out.flush(); } catch ( IOException e) { e.printStackTrace(); } }
Example 11
public static void saveJSONObject(JSONObject jsonObject) throws IOException { Log.i(AnkiDroidApp.TAG,"saveJSONObject"); BufferedWriter buff=new BufferedWriter(new FileWriter("/sdcard/jsonObjectAndroid.txt",true)); buff.write(jsonObject.toString()); buff.close(); }
Example 12
From project archaius, under directory /archaius-core/src/test/java/com/netflix/config/.
Source 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(); writer.close(); System.err.println(configFile.getPath() + " created"); return configFile; }
Example 13
From project BibleQuote-for-Android, under directory /src/com/BibleQuote/utils/.
Source file: Log.java

private static BufferedWriter GetWriter(){ try { OutputStreamWriter oWriter=new OutputStreamWriter(new FileOutputStream(logFile,true)); BufferedWriter bWriter=new BufferedWriter(oWriter); return bWriter; } catch ( FileNotFoundException e) { return null; } }
Example 14
From project BlameSubversion-plugin, under directory /src/main/java/hudson/scm/.
Source file: BlameSubversionSCM.java

private void writeChgLog(List<String> buffer,String filename) throws IOException { BufferedWriter writer=new BufferedWriter(new FileWriter(filename)); for ( String str : buffer) { writer.write(str); } writer.close(); }
Example 15
From project build-info, under directory /build-info-api/src/test/java/org/jfrog/build/api/.
Source file: FileChecksumCalculatorTest.java

/** * Tests the behavior of the calculator when given a valid file */ public void testValidFile() throws IOException, NoSuchAlgorithmException { File tempFile=File.createTempFile("moo","test"); BufferedWriter out=new BufferedWriter(new FileWriter(tempFile)); out.write("This is a test file"); out.close(); Map<String,String> checksumsMap=FileChecksumCalculator.calculateChecksums(tempFile,"md5","sha1"); String md5=getChecksum("md5",tempFile); String sha1=getChecksum("sha1",tempFile); assertEquals(checksumsMap.get("md5"),md5,"Unexpected test file MD5 checksum value."); assertEquals(checksumsMap.get("sha1"),sha1,"Unexpected test file SHA1 checksum value."); }
Example 16
/** * Write the settings to the CSV file * @throws Exception if file isn't found or error occurs */ private static boolean writeSettings() throws Exception { String data=m_settings.ToCSV(); FileWriter fw=new FileWriter("data/settings.csv"); BufferedWriter writer=new BufferedWriter(fw); writer.write(data); writer.close(); return true; }
Example 17
From project ceres, under directory /ceres-core/src/main/java/com/bc/ceres/core/runtime/internal/.
Source file: ModuleLoader.java

private void writeInstallInfo(File moduleDir,List<String> installedFiles) throws IOException { File installInfoFile=new File(moduleDir,ModuleInstaller.INSTALL_INFO_XML); BufferedWriter writer=new BufferedWriter(new FileWriter(installInfoFile)); try { InstallInfo installInfo=new InstallInfo(installedFiles.toArray(new String[0])); installInfo.write(writer); } finally { writer.close(); } }
Example 18
From project clustermeister, under directory /provisioning/src/main/java/com/github/nethad/clustermeister/provisioning/utils/.
Source file: FileUtils.java

/** * Write a {@link Properties} to a file. * @param comment A comment to add at the top of the file. * @param propertiesFile the properties file to write to. * @param properties the properties to write. * @throws FileNotFoundException when propertiesFile is not found or can not be created. * @throws IOException when propertiesFile can not be written to. */ public static void writePropertiesToFile(String comment,final File propertiesFile,Properties properties) throws FileNotFoundException, IOException { BufferedWriter fileWriter=Files.newWriter(propertiesFile,Charsets.UTF_8); try { properties.store(fileWriter,comment); } finally { if (fileWriter != null) { fileWriter.close(); } } }
Example 19
From project cw-advandroid, under directory /SystemServices/Alarm/src/com/commonsware/android/syssvc/alarm/.
Source file: AppService.java

@Override protected void doWakefulWork(Intent intent){ File log=new File(Environment.getExternalStorageDirectory(),"AlarmLog.txt"); try { BufferedWriter out=new BufferedWriter(new FileWriter(log.getAbsolutePath(),log.exists())); out.write(new Date().toString()); out.write("\n"); out.close(); } catch ( IOException e) { Log.e("AppService","Exception appending to log file",e); } }
Example 20
From project data-bus, under directory /databus-worker/src/test/java/com/inmobi/databus/distcp/.
Source file: TestDistCPBaseService.java

private void createInvalidData() throws IOException { localFs.mkdirs(testRoot); Path dataRoot=new Path(testRoot,service.getInputPath()); localFs.mkdirs(dataRoot); Path p=new Path(dataRoot,"file1-empty"); localFs.create(p); p=new Path(dataRoot,"file-with-junk-data"); FSDataOutputStream out=localFs.create(p); BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(out)); writer.write("junkfile-1\n"); writer.write("junkfile-2\n"); writer.close(); }
Example 21
From project datasalt-utils, under directory /src/test/java/com/datasalt/utils/mapred/crossproduct/.
Source file: TestCrossProductMapRed.java

private void createFirstDataSet() throws IOException, TException { BufferedWriter writer=new BufferedWriter(new FileWriter(INPUT_1)); writer.write("beer" + "\n"); writer.write("wine" + "\n"); writer.close(); }
Example 22
From project dawn-common, under directory /org.dawb.common.util/src/org/dawb/common/util/io/.
Source file: FileUtils.java

/** * @param file * @param text * @param encoding * @throws Exception */ public static void write(final File file,final String text,String encoding) throws Exception { BufferedWriter b=null; try { final OutputStream out=new FileOutputStream(file); final OutputStreamWriter writer=new OutputStreamWriter(out,encoding); b=new BufferedWriter(writer); b.write(text.toCharArray()); } finally { if (b != null) { b.close(); } } }
Example 23
From project dawn-isenciaui, under directory /com.isencia.passerelle.workbench.model.ui/src/main/java/com/isencia/passerelle/workbench/model/ui/utils/.
Source file: FileUtils.java

/** * @param file * @param text * @param encoding * @throws Exception */ public static void write(final File file,final String text,String encoding) throws Exception { BufferedWriter b=null; try { final OutputStream out=new FileOutputStream(file); final OutputStreamWriter writer=new OutputStreamWriter(out,encoding); b=new BufferedWriter(writer); b.write(text.toCharArray()); } finally { if (b != null) { b.close(); } } }
Example 24
From project DragonTravel, under directory /src/main/java/com/xemsdoom/mexdb/file/.
Source file: IOManager.java

/** * Writes the loaded content to the flatfile. */ public void writeContent(LinkedHashMap<String,String> newcontent){ this.content=newcontent; try { BufferedWriter writer=new BufferedWriter(new FileWriter(flatfile)); for ( Map.Entry<String,String> entry : this.content.entrySet()) { writer.write(entry.getKey().concat(" ").concat(entry.getValue())); writer.newLine(); } writer.close(); } catch ( Exception e) { e.printStackTrace(); } }
Example 25
From project Eclipse, under directory /com.mobilesorcery.sdk.builder.moblin/src/com/mobilesorcery/sdk/builder/linux/.
Source file: VariableResolver.java

/** * Copies an inputstream to a file, recursivly resolving variables while copying. * @param o Output file * @param i Input stream to parse and copy * @throws Exception If recursion is too deep or a variable isn't defined * @throws IOException Error while reading from stream/writing to file */ public void doParseCopyStream(File o,InputStream i) throws Exception, IOException { BufferedReader r=new BufferedReader(new InputStreamReader(i)); BufferedWriter w=new BufferedWriter(new BufferedWriter(new FileWriter(o))); while (r.ready() == true) w.write(doResolveString(r.readLine()) + "\n"); w.close(); }
Example 26
From project emuLib, under directory /src/main/java/emulib/plugins/compiler/.
Source file: HEXFileHandler.java

/** * Generates a Intel Hex file based on the cached program HashMap. * @param filename file name where to store the hex file * @throws java.io.IOException */ public void generateFile(String filename) throws java.io.IOException { String fileData=generateHEX(); BufferedWriter out=new BufferedWriter(new FileWriter(filename)); out.write(fileData); out.close(); }
Example 27
From project facebook-android-sdk, under directory /examples/stream/src/com/facebook/stream/.
Source file: FileIO.java

/** * Write the data to the file indicate by fileName. The file is created if it doesn't exist. * @param activity * @param data * @param fileName * @throws IOException */ public static void write(Activity activity,String data,String fileName) throws IOException { FileOutputStream fo=activity.openFileOutput(fileName,0); BufferedWriter bf=new BufferedWriter(new FileWriter(fo.getFD())); bf.write(data); bf.flush(); bf.close(); }
Example 28
From project Aardvark, under directory /aardvark-interactive/src/test/java/gw/vark/.
Source file: InteractiveShellTest.java

private static void writeToFile(File file,String content) throws IOException { BufferedWriter writer=null; try { writer=new BufferedWriter(new FileWriter(file)); writer.write(content); } finally { try { StreamUtil.close(writer); } catch ( IOException closeException) { closeException.printStackTrace(); } } file.setLastModified(advanceAndGetMockFSClock()); }
Example 29
From project AceWiki, under directory /src/ch/uzh/ifi/attempto/acewiki/core/.
Source file: OntologyExporter.java

/** * Writes the given string into the current output stream. * @param str The string to be written. * @throws IOException when an IO problem occurs. */ protected void write(String str) throws IOException { if (writer == null) { writer=new BufferedWriter(new OutputStreamWriter(outputStream)); } writer.write(str); }
Example 30
From project ACLS-protocol-library, under directory /aclslib/src/main/java/au/edu/uq/cmm/aclslib/message/.
Source file: AclsClient.java

public Response serverSendReceive(Request r) throws AclsException { try { Socket aclsSocket=new Socket(); try { aclsSocket.setSoTimeout(timeout); aclsSocket.connect(new InetSocketAddress(serverHost,serverPort),timeout); BufferedWriter w=new BufferedWriter(new OutputStreamWriter(aclsSocket.getOutputStream())); InputStream is=aclsSocket.getInputStream(); LOG.debug("Sending ACLS server request " + r.getType().name() + "("+ r.unparse(true)+ ")"); w.append(r.unparse(false) + "\r\n").flush(); return new ResponseReaderImpl().readWithStatusLine(is); } finally { aclsSocket.close(); } } catch ( SocketTimeoutException ex) { LOG.info("ACLS send / receive timed out"); throw new AclsNoResponseException("Timeout while connecting or talking to ACLS server (" + serverHost + ":"+ serverPort+ ")",ex); } catch ( IOException ex) { LOG.info("ACLS send / receive gave IO exception: " + ex.getMessage()); throw new AclsCommsException("IO error while trying to talk to ACLS server (" + serverHost + ":"+ serverPort+ ")",ex); } }
Example 31
From project AdminCmd, under directory /src/main/java/be/Balor/Tools/.
Source file: Downloader.java

void writeOnFile(final File file) throws IOException { BufferedWriter out=null; try { out=new BufferedWriter(new FileWriter(file)); out.write(version); out.write("\n"); out.write(String.valueOf(size)); out.flush(); } finally { try { if (out != null) { out.close(); } } catch ( final IOException e) { } } }
Example 32
From project agileBase, under directory /gtpb_server/src/com/gtwm/pb/util/.
Source file: Helpers.java

public static void writeFile(String fileName,String fileContents) throws IOException { Writer writer=new BufferedWriter(new FileWriter(fileName)); try { writer.write(fileContents); } finally { writer.close(); } }
Example 33
From project android-context, under directory /src/edu/fsu/cs/contextprovider/data/.
Source file: LogWriter.java

public LogWriter(String dest){ try { buff=new BufferedWriter(new FileWriter(dest,true)); } catch ( IOException e) { e.printStackTrace(); } }
Example 34
From project android-share-menu, under directory /src/com/eggie5/.
Source file: post_to_eggie5.java

private void SendRequest(String data_string){ try { String xmldata="<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<photo><photo>" + data_string + "</photo><caption>via android - "+ new Date().toString()+ "</caption></photo>"; String hostname="eggie5.com"; String path="/photos"; int port=80; InetAddress addr=InetAddress.getByName(hostname); Socket sock=new Socket(addr,port); BufferedWriter wr=new BufferedWriter(new OutputStreamWriter(sock.getOutputStream(),"UTF-8")); wr.write("POST " + path + " HTTP/1.1\r\n"); wr.write("Host: eggie5.com\r\n"); wr.write("Content-Length: " + xmldata.length() + "\r\n"); wr.write("Content-Type: text/xml; charset=\"utf-8\"\r\n"); wr.write("Accept: text/xml\r\n"); wr.write("\r\n"); wr.write(xmldata); wr.flush(); BufferedReader rd=new BufferedReader(new InputStreamReader(sock.getInputStream())); String line; while ((line=rd.readLine()) != null) { Log.v(this.getClass().getName(),line); } } catch ( Exception e) { Log.e(this.getClass().getName(),"Upload failed",e); } }
Example 35
From project AndroidCommon, under directory /src/com/asksven/android/common/utils/.
Source file: DataStorage.java

public static void LogToFile(String fileName,String strText){ try { File root=Environment.getExternalStorageDirectory(); if (root.canWrite()) { File dumpFile=new File(root,fileName); FileWriter fw=new FileWriter(dumpFile,true); BufferedWriter out=new BufferedWriter(fw); out.write(DateUtils.now() + " " + strText+ "\n"); out.close(); } } catch ( Exception e) { Log.e(TAG,"Exception: " + e.getMessage()); } }
Example 36
From project android_packages_apps_Gallery, under directory /tests/src/com/android/camera/stress/.
Source file: CameraStartUp.java

private void writeToOutputFile(String startupTag,long totalStartupTime,String individualStartupTime) throws Exception { try { FileWriter fstream=null; fstream=new FileWriter(CAMERA_TEST_OUTPUT_FILE,true); long averageStartupTime=totalStartupTime / TOTAL_NUMBER_OF_STARTUP; BufferedWriter out=new BufferedWriter(fstream); out.write(startupTag + "\n"); out.write("Number of loop: " + TOTAL_NUMBER_OF_STARTUP + "\n"); out.write(individualStartupTime + "\n\n"); out.write("Average startup time :" + averageStartupTime + " ms\n\n"); out.close(); fstream.close(); } catch ( Exception e) { fail("Camera write output to file"); } }
Example 37
From project android_packages_apps_VoiceDialer_2, under directory /src/com/android/voicedialer/.
Source file: RecognizerLogger.java

/** * Constructor * @param dataDir directory to contain the log files. */ public RecognizerLogger(Context context) throws IOException { if (false) Log.d(TAG,"RecognizerLogger"); File dir=context.getDir(LOGDIR,0); mDatedPath=dir.toString() + File.separator + "log_"+ DateFormat.format("yyyy_MM_dd_kk_mm_ss",System.currentTimeMillis()); deleteOldest(".wav"); deleteOldest(".log"); mWriter=new BufferedWriter(new FileWriter(mDatedPath + ".log"),8192); mWriter.write(Build.FINGERPRINT); mWriter.newLine(); }
Example 38
From project ANNIS, under directory /annis-service/src/main/java/annis/administration/.
Source file: CorpusAdministration.java

protected void writeDatabasePropertiesFile(String host,String port,String database,String user,String password){ File file=new File(System.getProperty("annis.home") + "/conf","database.properties"); try { BufferedWriter writer=new BufferedWriter(new FileWriterWithEncoding(file,"UTF-8")); writer.write("# database configuration\n"); writer.write("datasource.driver=org.postgresql.Driver\n"); writer.write("datasource.url=jdbc:postgresql://" + host + ":"+ port+ "/"+ database+ "\n"); writer.write("datasource.username=" + user + "\n"); writer.write("datasource.password=" + password + "\n"); writer.close(); } catch ( IOException e) { log.error("Couldn't write database properties file",e); throw new FileAccessException(e); } log.info("Wrote database configuration to " + file.getAbsolutePath()); }
Example 39
From project ant4eclipse, under directory /org.ant4eclipse.lib.jdt/src/org/ant4eclipse/lib/jdt/internal/model/jre/support/.
Source file: LibraryDetector.java

/** * Prints system properties to a file that must be specified in args[0]. <ul> <li>java.version</li> <li>sun.boot.class.path</li> <li>java.ext.dirs</li> <li>java.endorsed.dirs</li> </ul> * @param args */ public static void main(String[] args){ StringBuffer buffer=new StringBuffer(); buffer.append(System.getProperty("java.version")); buffer.append("|"); buffer.append(System.getProperty("sun.boot.class.path")); buffer.append("|"); buffer.append(System.getProperty("java.ext.dirs")); buffer.append("|"); buffer.append(System.getProperty("java.endorsed.dirs")); buffer.append("|"); buffer.append(System.getProperty("java.specification.version")); buffer.append("|"); buffer.append(System.getProperty("java.specification.name")); buffer.append("|"); buffer.append(System.getProperty("java.vendor")); System.out.println(buffer.toString()); try { File outfile=new File(args[0]); BufferedWriter out=new BufferedWriter(new FileWriter(outfile)); out.write(buffer.toString()); out.close(); } catch ( IOException e) { e.printStackTrace(); } }
Example 40
From project archive-commons, under directory /ia-tools/src/main/java/org/archive/hadoop/jobs/.
Source file: CDXTransformer.java

public static void main(String args[]) throws IOException { String line; BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out)); PrintWriter pw=new PrintWriter(bw); CDXTransformer t=new CDXTransformer(pw); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); if (args.length > 0) { if (args[0].equals("--no-massage")) { t.setCan(new NonMassagingIAURLCanonicalizer()); } } while (true) { line=br.readLine(); if (line == null) { break; } t.output(line); } pw.flush(); }
Example 41
From project artimate, under directory /artimate-demo/src/main/java/com/jdotsoft/jarloader/.
Source file: JarClassLoader.java

/** * Creates file with temporary files list. This list will be used to delete temporary files on the next application launch. The method is called from shutdown(). * @param fileCfg file with temporary files list. */ private void persistNewTemp(File fileCfg){ if (hsDeleteOnExit.size() == 0) { logDebug(LogArea.CONFIG,"No temp file names to persist on exit."); fileCfg.delete(); return; } logDebug(LogArea.CONFIG,"Persisting %d temp file names into %s",hsDeleteOnExit.size(),fileCfg.getAbsolutePath()); BufferedWriter writer=null; try { writer=new BufferedWriter(new FileWriter(fileCfg)); for ( File file : hsDeleteOnExit) { if (!file.delete()) { String f=file.getCanonicalPath(); writer.write(f); writer.newLine(); logWarn(LogArea.JAR,"JVM failed to release %s",f); } } } catch ( IOException e) { } finally { if (writer != null) { try { writer.close(); } catch ( IOException e) { } } } }
Example 42
From project asterisk-java, under directory /src/main/java/org/asteriskjava/util/internal/.
Source file: SocketConnectionFacadeImpl.java

private void initialize(Socket socket,Pattern pattern) throws IOException { this.socket=socket; InputStream inputStream=socket.getInputStream(); OutputStream outputStream=socket.getOutputStream(); BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream)); this.scanner=new Scanner(reader); this.scanner.useDelimiter(pattern); this.writer=new BufferedWriter(new OutputStreamWriter(outputStream)); }
Example 43
From project AuthDB, under directory /src/main/java/com/craftfire/util/managers/.
Source file: LoggingManager.java

private void ToFile(Type type,String line,String logFolder){ if (PluginManager.config.logging_enabled) { File data=new File(logFolder,""); if (!data.exists()) { if (data.mkdir()) { Util.logging.Debug("Created missing directory: " + logFolder); } } data=new File(logFolder + type.toString() + "/",""); if (!data.exists()) { if (data.mkdir()) { Util.logging.Debug("Created missing directory: " + logFolder + type.toString()); } } DateFormat LogFormat=new SimpleDateFormat(PluginManager.config.logformat); Date date=new Date(); data=new File(logFolder + type.toString() + "/"+ LogFormat.format(date)+ "-"+ type.toString()+ ".log"); if (!data.exists()) { try { data.createNewFile(); } catch ( IOException e) { Util.logging.StackTrace(e.getStackTrace(),Thread.currentThread().getStackTrace()[1].getMethodName(),Thread.currentThread().getStackTrace()[1].getLineNumber(),Thread.currentThread().getStackTrace()[1].getClassName(),Thread.currentThread().getStackTrace()[1].getFileName()); } } FileWriter Writer; try { DateFormat StringFormat=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date TheDate=new Date(); Writer=new FileWriter(logFolder + type.toString() + "/"+ LogFormat.format(date)+ "-"+ type.toString()+ ".log",true); BufferedWriter Out=new BufferedWriter(Writer); Out.write(StringFormat.format(TheDate) + " - " + line+ System.getProperty("line.separator")); Out.close(); } catch ( IOException e) { Util.logging.StackTrace(e.getStackTrace(),Thread.currentThread().getStackTrace()[1].getMethodName(),Thread.currentThread().getStackTrace()[1].getLineNumber(),Thread.currentThread().getStackTrace()[1].getClassName(),Thread.currentThread().getStackTrace()[1].getFileName()); } } }
Example 44
From project authme-2.0, under directory /src/uk/org/whoami/authme/datasource/.
Source file: FileDataSource.java

@Override public synchronized boolean saveAuth(PlayerAuth auth){ if (isAuthAvailable(auth.getNickname())) { return false; } BufferedWriter bw=null; try { bw=new BufferedWriter(new FileWriter(source,true)); bw.write(auth.getNickname() + ":" + auth.getHash()+ ":"+ auth.getIp()+ ":"+ auth.getLastLogin()+ "\n"); } catch ( IOException ex) { ConsoleLogger.showError(ex.getMessage()); return false; } finally { if (bw != null) { try { bw.close(); } catch ( IOException ex) { } } } return true; }
Example 45
From project AuthMe-Reloaded, under directory /src/main/java/uk/org/whoami/authme/datasource/.
Source file: FileDataSource.java

@Override public synchronized boolean saveAuth(PlayerAuth auth){ if (isAuthAvailable(auth.getNickname())) { return false; } BufferedWriter bw=null; try { if (auth.getQuitLocY() == 0) { bw=new BufferedWriter(new FileWriter(source,true)); bw.write(auth.getNickname() + ":" + auth.getHash()+ ":"+ auth.getIp()+ ":"+ auth.getLastLogin()+ "\n"); } else { bw=new BufferedWriter(new FileWriter(source,true)); bw.write(auth.getNickname() + ":" + auth.getHash()+ ":"+ auth.getIp()+ ":"+ auth.getLastLogin()+ ":"+ auth.getQuitLocX()+ ":"+ auth.getQuitLocY()+ ":"+ auth.getQuitLocZ()+ "\n"); } } catch ( IOException ex) { ConsoleLogger.showError(ex.getMessage()); return false; } finally { if (bw != null) { try { bw.close(); } catch ( IOException ex) { } } } return true; }
Example 46
From project AuthMe-Reloaded-Charge-fix, under directory /src/uk/org/whoami/authme/datasource/.
Source file: FileDataSource.java

@Override public synchronized boolean saveAuth(PlayerAuth auth){ if (isAuthAvailable(auth.getNickname())) { return false; } BufferedWriter bw=null; try { if (auth.getQuitLocY() == 0) { bw=new BufferedWriter(new FileWriter(source,true)); bw.write(auth.getNickname() + ":" + auth.getHash()+ ":"+ auth.getIp()+ ":"+ auth.getLastLogin()+ "\n"); } else { bw=new BufferedWriter(new FileWriter(source,true)); bw.write(auth.getNickname() + ":" + auth.getHash()+ ":"+ auth.getIp()+ ":"+ auth.getLastLogin()+ ":"+ auth.getQuitLocX()+ ":"+ auth.getQuitLocY()+ ":"+ auth.getQuitLocZ()+ "\n"); } } catch ( IOException ex) { ConsoleLogger.showError(ex.getMessage()); return false; } finally { if (bw != null) { try { bw.close(); } catch ( IOException ex) { } } } return true; }
Example 47
From project autopsy, under directory /Core/src/org/sleuthkit/autopsy/report/.
Source file: ReportHTML.java

@Override public void save(String path){ try { Writer out=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path),"UTF-8")); out.write(formatted_header.toString()); out.flush(); out.close(); } catch ( IOException e) { Logger.getLogger(ReportHTML.class.getName()).log(Level.WARNING,"Could not write out HTML report!",e); } }
Example 48
From project azkaban, under directory /azkaban/src/java/azkaban/flow/.
Source file: ImmutableFlowManager.java

@Override public FlowExecutionHolder saveExecutableFlow(FlowExecutionHolder holder){ File storageFile=new File(storageDirectory,String.format("%s.json",holder.getFlow().getId())); JSONObject jsonObj=new JSONObject(serializer.apply(holder)); BufferedWriter out=null; try { out=new BufferedWriter(new FileWriter(storageFile)); out.write(jsonObj.toString(2)); out.flush(); } catch ( Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(out); } return holder; }
Example 49
From project BabelCraft-Legacy, under directory /src/main/java/com/craftfire/babelcraft/util/managers/.
Source file: LoggingManager.java

private void ToFile(Type type,String line,String logFolder){ if (Config.plugin_logging) { File data=new File(logFolder,""); if (!data.exists()) { if (data.mkdir()) { debug("Created missing directory: " + logFolder); } } data=new File(logFolder + type.toString() + "/",""); if (!data.exists()) { if (data.mkdir()) { debug("Created missing directory: " + logFolder + type.toString()); } } DateFormat LogFormat=new SimpleDateFormat(Config.plugin_logformat); Date date=new Date(); data=new File(logFolder + type.toString() + "/"+ LogFormat.format(date)+ "-"+ type.toString()+ ".log"); if (!data.exists()) { try { data.createNewFile(); } catch ( IOException e) { stackTrace(e.getStackTrace(),Thread.currentThread().getStackTrace()[1].getMethodName(),Thread.currentThread().getStackTrace()[1].getLineNumber(),Thread.currentThread().getStackTrace()[1].getClassName(),Thread.currentThread().getStackTrace()[1].getFileName()); } } FileWriter Writer; try { DateFormat StringFormat=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date TheDate=new Date(); Writer=new FileWriter(logFolder + type.toString() + "/"+ LogFormat.format(date)+ "-"+ type.toString()+ ".log",true); BufferedWriter Out=new BufferedWriter(Writer); Out.write(StringFormat.format(TheDate) + " - " + line+ System.getProperty("line.separator")); Out.close(); } catch ( IOException e) { stackTrace(e.getStackTrace(),Thread.currentThread().getStackTrace()[1].getMethodName(),Thread.currentThread().getStackTrace()[1].getLineNumber(),Thread.currentThread().getStackTrace()[1].getClassName(),Thread.currentThread().getStackTrace()[1].getFileName()); } } }
Example 50
From project be.norio.twunch.android, under directory /src/be/norio/twunch/android/util/.
Source file: ViewServer.java

private static boolean writeValue(Socket client,String value){ boolean result; BufferedWriter out=null; try { OutputStream clientStream=client.getOutputStream(); out=new BufferedWriter(new OutputStreamWriter(clientStream),8 * 1024); out.write(value); out.write("\n"); out.flush(); result=true; } catch ( Exception e) { result=false; } finally { if (out != null) { try { out.close(); } catch ( IOException e) { result=false; } } } return result; }
Example 51
From project beam-meris-icol, under directory /src/main/java/org/esa/beam/meris/icol/graphgen/.
Source file: GraphGenMain.java

public static void main(String[] args) throws IOException { if (args.length < 3) { System.out.println("Usage: GraphGenMain <productPath> <graphmlPath> 'meris'|'landsat' [[<hideBands>] <hideProducts>]"); System.exit(1); } String productPath=args[0]; String graphmlPath=args[1]; String opSelector=args[2]; String hideBandsArg=args.length > 3 ? args[3] : null; String hideProductsArg=args.length > 4 ? args[4] : null; Operator op; if (opSelector.equalsIgnoreCase("meris")) { op=new MerisOp(); } else if (opSelector.equalsIgnoreCase("landsat")) { op=new TmOp(); } else { throw new IllegalArgumentException("argument 3 must be 'meris' or 'landsat'."); } final Product sourceProduct=ProductIO.readProduct(new File(productPath)); op.setSourceProduct(sourceProduct); final Product targetProduct=op.getTargetProduct(); FileWriter fileWriter=new FileWriter(new File(graphmlPath)); BufferedWriter writer=new BufferedWriter(fileWriter); final GraphGen graphGen=new GraphGen(); boolean hideBands=hideBandsArg != null && Boolean.parseBoolean(hideBandsArg); final boolean hideProducts=hideProductsArg != null && Boolean.parseBoolean(hideProductsArg); if (hideProducts) { hideBands=true; } GraphMLHandler handler=new GraphMLHandler(writer,hideBands,hideProducts); graphGen.generateGraph(targetProduct,handler); writer.close(); }
Example 52
public static BufferedWriter bufferWriter(Writer writer,int bufferSize){ if (writer instanceof BufferedWriter) { return (BufferedWriter)writer; } else { return new BufferedWriter(writer,adjustBufferSize(bufferSize)); } }
Example 53
From project behemoth, under directory /gate/src/main/java/com/digitalpebble/behemoth/gate/.
Source file: GATECorpusGenerator.java

private void generateXMLdocs(Path input,File dir,int[] count) throws IOException { Reader[] cacheReaders=SequenceFileOutputFormat.getReaders(getConf(),input); for ( Reader current : cacheReaders) { Text key=new Text(); BehemothDocument inputDoc=new BehemothDocument(); BufferedWriter writer=null; gate.Document gatedocument=null; while (current.next(key,inputDoc)) { count[0]++; try { GATEProcessor gp=new GATEProcessor(new URL("http://dummy.com")); gatedocument=gp.generateGATEDoc(inputDoc); File outputFile=new File(dir,count[0] + ".xml"); if (outputFile.exists() == false) outputFile.createNewFile(); writer=new BufferedWriter(new FileWriter(outputFile)); writer.write(gatedocument.toXml()); } catch ( Exception e) { LOG.error("Exception on doc [" + count[0] + "] "+ key.toString(),e); } finally { if (writer != null) writer.close(); if (gatedocument != null) Factory.deleteResource(gatedocument); } } current.close(); } }
Example 54
From project BetterShop_1, under directory /src/me/jascotty2/bettershop/.
Source file: Updater.java

static void setUpdatedFile(){ File versionFile=new File(BSConfig.pluginFolder,"lastUpdate"); FileWriter fstream=null; BufferedWriter out=null; try { versionFile.createNewFile(); fstream=new FileWriter(versionFile.getAbsolutePath()); out=new BufferedWriter(fstream); out.write(String.valueOf(System.currentTimeMillis())); } catch ( Exception ex) { BetterShopLogger.Log(Level.SEVERE,"Error saving update save file",ex); } finally { if (out != null) { try { out.close(); fstream.close(); } catch ( IOException ex) { } } } }
Example 55
From project BG7, under directory /src/com/era7/bioinfo/annotation/.
Source file: FixFastaHeaders.java

public static void main(String[] args){ if (args.length != 3) { System.out.println("This program expects three parameters: \n" + "1. Input FASTA file \n" + "2. Output FASTA file\n"+ "3. Project prefix\n"); } else { String inFileString=args[0]; String outFileString=args[1]; String projectPrefix=args[2]; File inFile=new File(inFileString); File outFile=new File(outFileString); try { BufferedWriter outBuff=new BufferedWriter(new FileWriter(outFile)); BufferedReader reader=new BufferedReader(new FileReader(inFile)); String line; int idCounter=1; while ((line=reader.readLine()) != null) { if (line.startsWith(">")) { outBuff.write(">" + projectPrefix + addUglyZeros(idCounter)+ " |"+ line.substring(1)+ "\n"); idCounter++; } else { outBuff.write(line + "\n"); } } reader.close(); outBuff.close(); System.out.println("Output fasta file created successfully! :D"); } catch ( Exception e) { e.printStackTrace(); } } }
Example 56
From project Bio4j, under directory /src/main/java/com/era7/bioinfo/bio4j/codesamples/.
Source file: GetGOAnnotationsForOrganism.java

public static void main(String[] args){ if (args.length != 3) { System.out.println("The program expects the following parameters: \n" + "1. Bio4j DB folder\n" + "2. Scientific name (Uniprot taxonomy)\n"+ "3. Output XML filename"); } else { Bio4jManager manager=null; try { System.out.println("Creating manager..."); manager=new Bio4jManager(args[0]); NodeRetriever nodeRetriever=new NodeRetriever(manager); File outFile=new File(args[2]); BufferedWriter writer=new BufferedWriter(new FileWriter(outFile)); System.out.println("Getting organism..."); OrganismNode organism=nodeRetriever.getOrganismByScientificName(args[1]); System.out.println("Organism found, ID: " + organism.getNcbiTaxonomyId()); ArrayList<ProteinXML> proteins=new ArrayList<ProteinXML>(); System.out.println("Getting proteins..."); for ( ProteinNode proteinNode : organism.getAssociatedProteins()) { ProteinXML proteinXML=new ProteinXML(); proteinXML.setId(proteinNode.getAccession()); proteins.add(proteinXML); } System.out.println("Looking for GO annotations..."); GoAnnotationXML goAnnotationXML=GoUtil.getGoAnnotation(proteins,manager); writer.write(XMLUtil.prettyPrintXML(goAnnotationXML.toString(),3)); writer.close(); System.out.println("Done! :)"); } catch ( Exception e) { e.printStackTrace(); } finally { manager.shutDown(); } } }
Example 57
/** * Opens the filename passed to the constructor for writing. */ public void openWriter(){ try { if (filename != null) { out=new BufferedWriter(new FileWriter(filename)); writer=true; } } catch ( IOException e) { System.err.println("There was a problem opening the requested file " + filename + "."); System.err.println("Error: " + e); System.exit(1); } }
Example 58
public boolean saveDocument(File output){ try { BufferedWriter w=new BufferedWriter(new FileWriter(output)); w.write(jEditorPane1.getText()); w.flush(); w.close(); this.docFile=output; this.docTitle=output.getName(); setCurrentDocModified(false); this.docNew=false; return true; } catch ( IOException ioe) { showError("BMach - Error","I/O error:","An error occured while trying to save the file"); return false; } }
Example 59
From project bundlemaker, under directory /main/org.bundlemaker.core.reports/src/org/bundlemaker/core/reports/exporter/html/.
Source file: AbstractSingleModuleHtmlReportExporter.java

/** * {@inheritDoc} */ @Override protected void doExport(IProgressMonitor progressMonitor) throws CoreException { SubMonitor subMonitor=SubMonitor.convert(progressMonitor,3); subMonitor.beginTask(null,3); _rootArtifact=getCurrentModularizedSystem().getArtifactModel(getModelConfiguration()); try { File file=new File(getCurrentContext().getDestinationDirectory(),getReportName() + ".html"); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } BufferedWriter bufferedWriter=getBufferedWriter(file); writeHtmlHead(bufferedWriter); writeHtmlBody(bufferedWriter); bufferedWriter.flush(); bufferedWriter.close(); subMonitor.worked(2); } catch ( Exception e) { e.printStackTrace(); throw new CoreException(new Status(IStatus.ERROR,"","")); } }
Example 60
From project c10n, under directory /tools/src/main/java/c10n/tools/codegen/.
Source file: DefaultCodeGenerator.java

private void generateSourceFile(Class<?> c10nInterface,Map<String,String> translations,String targetPackage,File targetFolder,String localeSuffix) throws IOException { String typeName; if (null != localeSuffix) { typeName=c10nInterface.getSimpleName() + "_" + localeSuffix+ "_impl"; } else { typeName=c10nInterface.getSimpleName() + "_impl"; } CompilationUnit cu=new CompilationUnit(); cu.setPackage(new PackageDeclaration(ASTHelper.createNameExpr(targetPackage))); TypeDeclaration typeDec=convert(c10nInterface,typeName,translations,localeSuffix); ASTHelper.addTypeDeclaration(cu,typeDec); File outputJavaFile=new File(targetFolder,typeName + ".java"); FileOutputStream fos=null; try { fos=new FileOutputStream(outputJavaFile); BufferedWriter w=new BufferedWriter(new OutputStreamWriter(fos)); w.append(cu.toString()); w.flush(); } finally { if (null != fos) { fos.close(); } } }
Example 61
From project Cafe, under directory /testservice/src/com/baidu/cafe/remote/.
Source file: SystemLib.java

/** * write a line of string to a file in the sdcard * @param filename : file name in the sdcard to write * @param line : string to write */ public void writeLineToSdcard(String filename,String line){ final String outputFile=Environment.getExternalStorageDirectory().toString() + "/" + filename; try { FileWriter fstream=null; fstream=new FileWriter(outputFile,true); BufferedWriter out=new BufferedWriter(fstream); out.write(line + "\n"); out.close(); fstream.close(); Log.print("write log: " + outputFile); } catch ( Exception e) { Log.print("exception for write log"); } }
Example 62
From project Carolina-Digital-Repository, under directory /fcrepo-clients/src/main/java/edu/unc/lib/dl/fedora/.
Source file: ClientUtils.java

/** * Serializes a JDOM element to a UTF-8 encoded file. Does not enforce locally declared namespaces. * @param element a detached, standalone element * @return */ public static File writeXMLToTempFile(Element element) throws IOException { Format format=Format.getPrettyFormat(); XMLOutputter outputter=new XMLOutputter(format); BufferedWriter writer=null; try { File result=File.createTempFile("ClientUtils-",".xml"); writer=new BufferedWriter(new FileWriter(result)); outputter.output(element,writer); return result; } finally { if (writer != null) { try { writer.close(); } catch ( IOException e) { log.error("Failed to close temp file",e); } } } }
Example 63
public void saveMap(String filename){ File f=new File(filename); try { FileWriter fstream=new FileWriter(f); BufferedWriter out=new BufferedWriter(fstream); int num=0; for ( CatLevel l : levels) { out.write("LEVEL," + (num++) + "\r\n"); out.write("WORLD," + world.getName() + "\r\n"); List<String> map=l.getMap(); for ( String s : map) { out.write(s + "\r\n"); } out.write("\r\n"); } out.close(); } catch ( Exception e) { System.err.println(e.getMessage()); } }
Example 64
From project Catroid-maven-playground, under directory /src/main/java/at/tugraz/ist/catroid/io/.
Source file: StorageHandler.java

public boolean saveProject(Project project){ createCatroidRoot(); if (project == null) { return false; } try { String projectFile=xstream.toXML(project); String projectDirectoryName=Utils.buildProjectPath(project.getName()); File projectDirectory=new File(projectDirectoryName); if (!(projectDirectory.exists() && projectDirectory.isDirectory() && projectDirectory.canWrite())) { projectDirectory.mkdir(); File imageDirectory=new File(Utils.buildPath(projectDirectoryName,Constants.IMAGE_DIRECTORY)); imageDirectory.mkdir(); File noMediaFile=new File(Utils.buildPath(projectDirectoryName,Constants.IMAGE_DIRECTORY,Constants.NO_MEDIA_FILE)); noMediaFile.createNewFile(); File soundDirectory=new File(projectDirectoryName + "/" + Constants.SOUND_DIRECTORY); soundDirectory.mkdir(); noMediaFile=new File(Utils.buildPath(projectDirectoryName,Constants.SOUND_DIRECTORY,Constants.NO_MEDIA_FILE)); noMediaFile.createNewFile(); } BufferedWriter writer=new BufferedWriter(new FileWriter(Utils.buildPath(projectDirectoryName,Constants.PROJECTCODE_NAME)),Constants.BUFFER_8K); writer.write(XML_HEADER.concat(projectFile)); writer.flush(); writer.close(); return true; } catch ( Exception e) { e.printStackTrace(); Log.e(TAG,"saveProject threw an exception and failed."); return false; } }
Example 65
From project chukwa, under directory /src/test/java/org/apache/hadoop/chukwa/tools/backfilling/.
Source file: TestBackfillingLoader.java

protected long validateDataSink(FileSystem fs,Configuration conf,String dataSinkFile,File logFile,String cluster,String dataType,String source,String application) throws Throwable { SequenceFile.Reader reader=null; long lastSeqId=-1; BufferedWriter out=null; try { reader=new SequenceFile.Reader(fs,new Path(dataSinkFile),conf); ChukwaArchiveKey key=new ChukwaArchiveKey(); ChunkImpl chunk=ChunkImpl.getBlankChunk(); String dataSinkDumpName=dataSinkFile + ".dump"; out=new BufferedWriter(new FileWriter(dataSinkDumpName)); while (reader.next(key,chunk)) { Assert.assertTrue(cluster.equals(RecordUtil.getClusterName(chunk))); Assert.assertTrue(dataType.equals(chunk.getDataType())); Assert.assertTrue(source.equals(chunk.getSource())); out.write(new String(chunk.getData())); lastSeqId=chunk.getSeqID(); } out.close(); out=null; reader.close(); reader=null; String dataSinkMD5=MD5.checksum(new File(dataSinkDumpName)); String logFileMD5=MD5.checksum(logFile); Assert.assertTrue(dataSinkMD5.equals(logFileMD5)); } finally { if (out != null) { out.close(); } if (reader != null) { reader.close(); } } return lastSeqId; }
Example 66
/** * Write a String to a file (used for string representation of lists). * @param listFile the file to write to * @param out the String to write * @return returns <code>true</code> if successful, <code>false</code> otherwise */ public static boolean writeList(final File listFile,final String out){ BufferedWriter bw=null; try { bw=new BufferedWriter(new PrintWriter(new FileWriter(listFile))); bw.write(out); bw.close(); return true; } catch ( final IOException e) { return false; } finally { if (bw != null) try { bw.close(); } catch ( final Exception e) { } } }
Example 67
From project cilia-workbench, under directory /cilia-workbench-designer/src/fr/liglab/adele/cilia/workbench/designer/service/common/.
Source file: AbstractRepoService.java

/** * Creates a new file in the repository. This method follows {@link IInputValidator#isValid(String)} API. * @param fileName the file name * @param content the file content * @return null if success, an error message otherwise. */ public String createFile(String fileName){ File destination=new File(getRepositoryLocation(),fileName); if (isNewFileNameAllowed(fileName) != null) return "file name is not allowed : " + isNewFileNameAllowed(fileName); boolean hasError=false; BufferedWriter out=null; try { out=new BufferedWriter(new FileWriter(destination)); out.write(getContentForNewFile()); } catch ( IOException e) { e.printStackTrace(); hasError=true; } if (out != null) { try { out.close(); } catch ( IOException e) { hasError=true; e.printStackTrace(); } } updateModel(); if (hasError) return "i/o error while writing file"; else return null; }
Example 68
From project CIShell, under directory /testing/org.cishell.testing.convertertester.core.new/src/org/cishell/testing/convertertester/core/converter/graph/.
Source file: ConverterGraph.java

public File asNWB(){ Map nodes=assembleNodesSet(); TreeSet edges=assembleEdges(nodes); File f=getTempFile(); try { BufferedWriter writer=new BufferedWriter(new FileWriter(f)); writeNodes(writer,nodes); writeEdges(writer,edges); } catch ( IOException e) { System.out.println("Blurt!"); this.log.log(LogService.LOG_ERROR,"IOException while creating converter graph file",e); } return f; }
Example 69
From project Clotho-Core, under directory /ClothoApps/SeqAnalyzer/src/org/clothocad/algorithm/seqanalyzer/sequencing/.
Source file: seqAnalysis.java

private void file(String datafile,String filename){ try { Writer output=null; File file=new File(filename); output=new BufferedWriter(new FileWriter(file)); output.write(datafile); output.close(); } catch ( IOException ex) { Logger.getLogger(seqAnalysis.class.getName()).log(Level.SEVERE,null,ex); System.out.println("*****IOException in file writer"); } }
Example 70
From project Cloud9, under directory /src/dist/edu/umd/hooka/.
Source file: CreateWordAlignmentCorpus.java

WriterCallback(String e,String f,String l) throws IOException { ew=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(e),"UTF8")); fw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f),"UTF8")); lw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(l),"UTF8")); sawp=AlignmentWordPreprocessor.CreatePreprocessor(lp,ar,null); tawp=AlignmentWordPreprocessor.CreatePreprocessor(lp,en,null); }
Example 71
From project cloudify, under directory /CLI/src/main/java/org/cloudifysource/shell/installer/.
Source file: LocalhostGridAgentBootstrapper.java

private File createScript(final String text) throws CLIException { File tempFile; try { tempFile=File.createTempFile("run-gs-agent",isWindows() ? ".bat" : ".sh"); } catch ( final IOException e) { throw new CLIException(e); } tempFile.deleteOnExit(); BufferedWriter out=null; try { try { out=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile))); if (!isWindows()) { out.write(LINUX_SCRIPT_PREFIX); } out.write(text); } finally { if (out != null) { out.close(); } } } catch ( final IOException e) { throw new CLIException(e); } if (!isWindows()) { tempFile.setExecutable(true,true); } return tempFile; }
Example 72
From project codjo-webservices, under directory /codjo-webservices-generator/src/main/java/net/codjo/webservices/generator/.
Source file: ClassListGenerator.java

public void generate(File sourcesDirectory,File targetDirectory,String packageName) throws IOException { File targetPackage=new File(sourcesDirectory,packageName.replace('.','/')); File resourcesDirectory=new File(targetDirectory,"resources"); if (!resourcesDirectory.exists()) { resourcesDirectory.mkdirs(); } File sourcesListFile=new File(resourcesDirectory,"sourcesList.txt"); BufferedWriter out=new BufferedWriter(new FileWriter(sourcesListFile,true)); File[] files=targetPackage.listFiles(new FileFilter(){ public boolean accept( File pathname){ return pathname.getName().endsWith(".java"); } } ); for ( File file : files) { String className=file.getAbsolutePath(); className=className.substring(targetDirectory.getAbsolutePath().length() + 1,className.length() - 5); out.write(className.replace(File.separator,".")); out.newLine(); } out.close(); }
Example 73
From project cogroo4, under directory /cogroo-eval/BaselineCogrooAE/src/main/java/cogroo/.
Source file: ProcessReport.java

private void processFile() throws IOException { BufferedReader in=new BufferedReader(new InputStreamReader(new FileInputStream(this.report),"utf-8")); BufferedWriter out=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(this.output),"utf-8")); String line=in.readLine(); while (line != null) { out.append(line).append("\n"); String text=getText(line); if (text != null) { out.append(process(text)).append("\n\n"); } line=in.readLine(); } in.close(); out.close(); }
Example 74
From project contribution_eevolution_warehouse_management, under directory /extension/eevolution/warehousemanagement/src/main/java/org/compiere/print/.
Source file: ReportEngine.java

/** * Create CSV File * @param file file * @param delimiter delimiter, e.g. comma, tab * @param language translation language * @return true if success */ public boolean createCSV(File file,char delimiter,Language language){ try { Writer fw=new OutputStreamWriter(new FileOutputStream(file,false),Ini.getCharset()); return createCSV(new BufferedWriter(fw),delimiter,language); } catch ( FileNotFoundException fnfe) { log.log(Level.SEVERE,"(f) - " + fnfe.toString()); } catch ( Exception e) { log.log(Level.SEVERE,"(f)",e); } return false; }
Example 75
public boolean append(String directory,String file,String[] lines){ BufferedWriter output; String line; this.existsCreate(directory,file); try { output=new BufferedWriter(new FileWriter(new File(directory,file),true)); try { for ( String append : lines) { output.write(append); output.newLine(); } } catch ( IOException ex) { this.log(Level.SEVERE,ex); output.close(); return false; } output.close(); return true; } catch ( FileNotFoundException ex) { this.log(Level.SEVERE,ex); } catch ( IOException ex) { this.log(Level.SEVERE,ex); } return false; }
Example 76
From project cornerstone, under directory /frameworks/base/services/java/com/android/server/wm/.
Source file: WindowManagerService.java

/** * Lists all availble windows in the system. The listing is written in the specified Socket's output stream with the following syntax: windowHashCodeInHexadecimal windowName Each line of the ouput represents a different window. * @param client The remote client to send the listing to. * @return False if an error occured, true otherwise. */ boolean viewServerListWindows(Socket client){ if (isSystemSecure()) { return false; } boolean result=true; WindowState[] windows; synchronized (mWindowMap) { windows=mWindows.toArray(new WindowState[mWindows.size()]); } BufferedWriter out=null; try { OutputStream clientStream=client.getOutputStream(); out=new BufferedWriter(new OutputStreamWriter(clientStream),8 * 1024); final int count=windows.length; for (int i=0; i < count; i++) { final WindowState w=windows[i]; out.write(Integer.toHexString(System.identityHashCode(w))); out.write(' '); out.append(w.mAttrs.getTitle()); out.write('\n'); } out.write("DONE.\n"); out.flush(); } catch ( Exception e) { result=false; } finally { if (out != null) { try { out.close(); } catch ( IOException e) { result=false; } } } return result; }
Example 77
From project cpptasks-parallel, under directory /src/main/java/net/sf/antcontrib/cpptasks/.
Source file: DependencyTable.java

public void commit(CCTask task){ if (dirty) { Vector includePaths=getIncludePaths(); try { FileOutputStream outStream=new FileOutputStream(dependenciesFile); OutputStreamWriter streamWriter; String encodingName="UTF-8"; try { streamWriter=new OutputStreamWriter(outStream,"UTF-8"); } catch ( UnsupportedEncodingException ex) { streamWriter=new OutputStreamWriter(outStream); encodingName=streamWriter.getEncoding(); } BufferedWriter writer=new BufferedWriter(streamWriter); writer.write("<?xml version='1.0' encoding='"); writer.write(encodingName); writer.write("'?>\n"); writer.write("<dependencies>\n"); StringBuffer buf=new StringBuffer(); Enumeration includePathEnum=includePaths.elements(); while (includePathEnum.hasMoreElements()) { writeIncludePathDependencies((String)includePathEnum.nextElement(),writer,buf); } writer.write("</dependencies>\n"); writer.close(); dirty=false; } catch ( IOException ex) { task.log("Error writing " + dependenciesFile.toString() + ":"+ ex.toString()); } } }
Example 78
From project CraftCommons, under directory /src/main/java/com/craftfire/commons/managers/.
Source file: LoggingManager.java

private void toFile(Type type,String line){ if (this.logging) { File data=new File(this.directory,""); if (!data.exists()) { if (data.mkdir()) { debug("Created missing directory: " + this.directory); } } data=new File(this.directory + type.toString() + "/",""); if (!data.exists()) { if (data.mkdir()) { debug("Created missing directory: " + this.directory + type.toString()); } } DateFormat logFormat=new SimpleDateFormat(this.format); Date date=new Date(); data=new File(this.directory + type.toString() + "/"+ logFormat.format(date)+ "-"+ type.toString()+ ".log"); if (!data.exists()) { try { data.createNewFile(); } catch ( IOException e) { stackTrace(e); } } try { DateFormat stringFormat=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); FileWriter writer=new FileWriter(this.directory + type.toString() + "/"+ logFormat.format(date)+ "-"+ type.toString()+ ".log",true); BufferedWriter buffer=new BufferedWriter(writer); buffer.write(stringFormat.format(date) + " - " + line+ System.getProperty("line.separator")); buffer.close(); writer.close(); } catch ( IOException e) { stackTrace(e); } } }
Example 79
From project Cyborg, under directory /src/main/java/com/alta189/cyborg/api/util/config/yaml/.
Source file: YamlConfiguration.java

@Override protected void saveFromMap(Map<?,?> map) throws ConfigurationException { BufferedWriter writer=null; File parent=file.getParentFile(); if (parent != null) { parent.mkdirs(); } try { writer=new BufferedWriter(getWriter()); if (getHeader() != null) { writer.append(getHeader()); writer.append(LINE_BREAK); } yaml.dump(map,writer); } catch ( YAMLException e) { throw new ConfigurationException(e); } catch ( IOException e) { throw new ConfigurationException(e); } finally { try { if (writer != null) { writer.flush(); writer.close(); } } catch ( IOException e) { } } }
Example 80
From project daap, under directory /src/main/java/org/ardverk/daap/tools/.
Source file: ChunkFactoryGenerator.java

public static void main(String[] args) throws Exception { StringBuffer buffer=new StringBuffer(); buffer.append(CLASS_COMMENT); buffer.append("\n"); buffer.append("package ").append(ChunkUtil.CHUNK_PACKAGE).append(";\n"); buffer.append("\n"); buffer.append("import java.util.HashMap;\n"); buffer.append("import de.kapsi.net.daap.DaapUtil;\n"); buffer.append("\n"); buffer.append("public final class ").append(CLASS).append(" {\n\n"); buffer.append(" private final HashMap map = new HashMap();\n\n"); buffer.append(" public ").append(CLASS).append("() {\n"); Chunk[] chunks=ChunkUtil.getChunks(); for (int i=0; i < chunks.length; i++) { Chunk chunk=chunks[i]; String contentCode="0x" + Integer.toHexString(chunk.getContentCode()).toUpperCase(Locale.US); String contentCodeString=chunk.getContentCodeString(); buffer.append(" "); buffer.append("map.put(new Integer(").append(contentCode).append("), ").append(chunk.getClass().getName()).append(".class); //").append(contentCodeString); buffer.append("\n"); } buffer.append(" }\n\n"); buffer.append(" public Class getChunkClass(Integer contentCode) {\n"); buffer.append(" return (Class)map.get(contentCode);\n"); buffer.append(" }\n\n"); buffer.append(" public Chunk newChunk(int contentCode) {\n"); buffer.append(" Class clazz = getChunkClass(new Integer(contentCode));\n"); buffer.append(" try {\n"); buffer.append(" return (Chunk)clazz.newInstance();\n"); buffer.append(" } catch (Exception err) {\n"); buffer.append(" throw new RuntimeException(DaapUtil.toContentCodeString(contentCode), err);\n"); buffer.append(" }\n"); buffer.append(" }\n"); buffer.append("}\n"); System.out.println(buffer); BufferedWriter out=new BufferedWriter(new FileWriter(new File(FILE))); out.write(buffer.toString()); out.close(); }
Example 81
From project datavalve, under directory /datavalve-dataset/src/test/java/org/fluttercode/datavalve/provider/file/.
Source file: CommaDelimitedDatasetTest.java

private void generateFile(){ baseDir=System.getProperty("java.io.tmpdir") + "/CsvDsTest/"; fileName=baseDir + "csvFile.csv"; File base=new File(baseDir); base.mkdir(); FileOutputStream fs=null; try { fs=new FileOutputStream(new File(fileName)); BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(fs)); for (int i=0; i < 100; i++) { writer.write(Integer.toString(i + 1)); writer.write(","); writer.write(getDataFactory().getFirstName()); writer.write(","); writer.write(getDataFactory().getLastName()); writer.write(","); writer.write(getDataFactory().getNumberText(10)); writer.newLine(); } writer.close(); } catch ( IOException e) { e.printStackTrace(); } }
Example 82
From project dawn-isencia, under directory /com.isencia.passerelle.engine/src/main/java/com/isencia/passerelle/model/.
Source file: FlowManager.java

/** * For locally managed flows, saves the flow's moml on the given URL (which should point to a local file). For remotely managed flows, updates the flow on the remote Passerelle Manager. Then the url parameter is ignored. * @param flow * @param url * @return the updated/saved flow (if it's a remote one, then with updatedFlowHandle) * @throws IOException * @throws PasserelleException */ public static Flow save(final Flow flow,final URL url) throws IOException, PasserelleException, Exception { if (!flow.getHandle().isRemote()) { FlowManager.writeMoml(flow,new BufferedWriter(new FileWriter(url.getFile()))); return flow; } else { if (restFacade == null) { initRESTFacade(); } FlowHandle updatedhandle=restFacade.updateRemoteFlow(flow); return buildFlowFromHandle(updatedhandle); } }
Example 83
From project dawn-ui, under directory /org.dawb.workbench.plotting/src/org/dawb/workbench/plotting/tools/fitting/.
Source file: FittingTool.java

/** * Will export to file and overwrite. Will append ".csv" if it is not already there. * @param path */ String exportFittedPeaks(final String path) throws Exception { File file=new File(path); if (!file.getName().toLowerCase().endsWith(".dat")) file=new File(path + ".dat"); if (file.exists()) file.delete(); final BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),"UTF-8")); try { writer.write(FittedPeak.getCVSTitle()); writer.newLine(); for ( FittedPeak peak : this.fittedPeaks.getPeakList()) { writer.write(peak.getTabString()); writer.newLine(); } } finally { writer.close(); } return file.getAbsolutePath(); }
Example 84
From project dcm4che, under directory /dcm4che-tool/dcm4che-tool-ihe/dcm4che-tool-ihe-modality/src/main/java/org/dcm4che/tool/ihe/modality/.
Source file: Modality.java

private static void scanFiles(List<String> fnames,String tmpPrefix,String tmpSuffix,File tmpDir,final MppsSCU mppsscu,final StoreSCU storescu,final StgCmtSCU stgcmtscu) throws IOException { printNextStepMessage("Will now scan files in " + fnames); File tmpFile=File.createTempFile(tmpPrefix,tmpSuffix,tmpDir); tmpFile.deleteOnExit(); final BufferedWriter fileInfos=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tmpFile))); try { DicomFiles.scan(fnames,new DicomFiles.Callback(){ @Override public boolean dicomFile( File f, long dsPos, String tsuid, Attributes ds) throws Exception { return mppsscu.addInstance(ds) && storescu.addFile(fileInfos,f,dsPos,ds,tsuid) && stgcmtscu.addInstance(ds); } } ); storescu.setTmpFile(tmpFile); } finally { fileInfos.close(); } System.out.println(" Done"); }
Example 85
From project des, under directory /daemon/lib/apache-log4j-1.2.16/contribs/LeosLiterak/.
Source file: TempFileAppender.java

/** * This method does actual writing */ protected void subAppend(LoggingEvent event){ try { File tmp=File.createTempFile(prefix,suffix,dir); Writer out=new BufferedWriter(new FileWriter(tmp)); out.write(event.message); out.close(); } catch ( Exception e) { errorHandler.error("Error during creation of temporary File!",e,1); } }
Example 86
From project dmix, under directory /LastFM-java/src/de/umass/lastfm/scrobble/.
Source file: Scrobbler.java

/** * 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 87
From project drools-planner, under directory /drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/.
Source file: AbstractTxtSolutionExporter.java

public void writeSolution(Solution solution,File outputFile){ BufferedWriter bufferedWriter=null; try { bufferedWriter=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile),"UTF-8")); TxtOutputBuilder txtOutputBuilder=createTxtOutputBuilder(); txtOutputBuilder.setBufferedWriter(bufferedWriter); txtOutputBuilder.setSolution(solution); txtOutputBuilder.writeSolution(); } catch ( IOException e) { throw new IllegalArgumentException("Could not write the file (" + outputFile.getName() + ").",e); } finally { IOUtils.closeQuietly(bufferedWriter); } logger.info("Exported: {}",outputFile); }
Example 88
From project DTRules, under directory /compilerutil/src/main/java/com/dtrules/compiler/excel/util/.
Source file: ImportRuleSets.java

public void setContents(File aFile,String aContents) throws FileNotFoundException, IOException { if (aFile == null) { throw new IllegalArgumentException("File should not be null."); } Writer output=null; try { output=new BufferedWriter(new FileWriter(aFile)); output.write(aContents); } finally { if (output != null) output.close(); } }
Example 89
From project eclim, under directory /org.eclim.core/test/junit/org/eclim/plugin/core/command/history/.
Source file: HistoryCommandTest.java

/** * Test the command. */ @Test @SuppressWarnings("unchecked") public void execute() throws Exception { String result=(String)Eclim.execute(new String[]{"history_clear","-p",Eclim.TEST_PROJECT,"-f",TEST_FILE}); assertEquals(result,"History Cleared."); List<Map<String,Object>> results=(List<Map<String,Object>>)Eclim.execute(new String[]{"history_list","-p",Eclim.TEST_PROJECT,"-f",TEST_FILE}); assertEquals(0,results.size()); assertEquals("Wrong file contents.",Eclim.fileToString(Eclim.TEST_PROJECT,TEST_FILE),"line 1\n"); Eclim.execute(new String[]{"history_add","-p",Eclim.TEST_PROJECT,"-f",TEST_FILE}); Eclim.execute(new String[]{"project_refresh_file","-p",Eclim.TEST_PROJECT,"-f",TEST_FILE}); BufferedWriter out=null; try { out=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(Eclim.resolveFile(TEST_FILE),true))); out.write("line 2"); } finally { try { out.close(); } catch ( Exception ignore) { } } Eclim.execute(new String[]{"history_add","-p",Eclim.TEST_PROJECT,"-f",TEST_FILE}); Eclim.execute(new String[]{"project_refresh_file","-p",Eclim.TEST_PROJECT,"-f",TEST_FILE}); results=(List<Map<String,Object>>)Eclim.execute(new String[]{"history_list","-p",Eclim.TEST_PROJECT,"-f",TEST_FILE}); assertEquals(2,results.size()); for ( Map<String,Object> entry : results) { assertTrue(ENTRY_TIMESTAMP.matcher(entry.get("timestamp").toString()).matches()); assertTrue(ENTRY_DATETIME.matcher(entry.get("datetime").toString()).matches()); assertTrue(ENTRY_DELTA.matcher(entry.get("delta").toString()).matches()); } result=(String)Eclim.execute(new String[]{"history_revision","-p",Eclim.TEST_PROJECT,"-f",TEST_FILE,"-r",results.get(1).get("timestamp").toString()}); assertEquals("Wrong result.",result,"line 1\n"); }
Example 90
From project eclipsefp, under directory /net.sf.eclipsefp.haskell.scion.client/src/net/sf/eclipsefp/haskell/scion/internal/client/.
Source file: ScionServer.java

private void connectToServer() throws ScionServerConnectException { try { socket=connectToServer(host,port); socketReader=new BufferedReader(new InputStreamReader(socket.getInputStream())); socketWriter=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); } catch ( Throwable ex) { throw new ScionServerConnectException(UITexts.scionServerConnectError_message,ex); } }
Example 91
From project elephant-twin, under directory /com.twitter.elephanttwin/src/main/java/com/twitter/elephanttwin/util/.
Source file: HdfsUtils.java

/** * Write \n separated lines of text to HDFS as UTF-8. */ public static void writeLines(FileSystem fs,Path path,Iterable<String> lines) throws IOException { Preconditions.checkNotNull(fs); Preconditions.checkNotNull(path); Preconditions.checkNotNull(lines); Writer stream=new BufferedWriter(new OutputStreamWriter(fs.create(path),"UTF-8")); try { for ( String line : lines) { stream.write(line + "\n"); } } finally { stream.close(); } }
Example 92
From project empire-db, under directory /empire-db-codegen/src/main/java/org/apache/empire/db/codegen/util/.
Source file: FileUtils.java

public static void writeStringToFile(File file,String contents){ BufferedWriter bw=null; try { if (!file.exists()) { file.createNewFile(); } bw=new BufferedWriter(new FileWriter(file)); bw.write(contents); } catch ( IOException e) { log.error(e.getMessage(),e); } finally { close(bw); } }
Example 93
@Override public void run(){ InputStreamReader isr=null; BufferedReader in=null; OutputStreamWriter osw=null; BufferedWriter out=null; try { isr=new InputStreamReader(_socket.getInputStream()); in=new BufferedReader(isr); osw=new OutputStreamWriter(_socket.getOutputStream()); out=new BufferedWriter(osw); String cmd=null; while (null != (cmd=in.readLine())) { TelnetCommandResult result=TelnetCommandExecutor.getInstance().execute(cmd); out.write(result.getCode() + " " + result.getCodeMessage()+ "\r\n"); out.write(result.getResult() + "\r\n"); out.flush(); } } catch ( IOException e) { StreamUtil.close(isr,in); StreamUtil.close(osw,out); } try { _socket.close(); } catch ( IOException e) { } }
Example 94
From project faces, under directory /Proyectos/01-jsf-solution/src/main/java/accounts/testdb/.
Source file: TestDataSourceFactory.java

private String parseSqlIn(Resource resource) throws IOException { InputStream is=null; try { is=resource.getInputStream(); BufferedReader reader=new BufferedReader(new InputStreamReader(is)); StringWriter sw=new StringWriter(); BufferedWriter writer=new BufferedWriter(sw); for (int c=reader.read(); c != -1; c=reader.read()) { writer.write(c); } writer.flush(); return sw.toString(); } finally { if (is != null) { is.close(); } } }
Example 95
From project Aion-Extreme, under directory /AE-go_GameServer/src/com/aionemu/gameserver/dataholders/loadingutils/.
Source file: XmlMerger.java

/** * This method processes the source file, replacing all of the 'import' tags by the data from the relevant files. * @throws XMLStreamException on event writing error. * @throws IOException if the destination file exists but is a directory rather thana regular file, does not exist but cannot be created, or cannot be opened for any other reason */ private void doUpdate() throws XMLStreamException, IOException { XMLEventReader reader=null; XMLEventWriter writer=null; Properties metadata=new Properties(); try { writer=outputFactory.createXMLEventWriter(new BufferedWriter(new FileWriter(destFile,false))); reader=inputFactory.createXMLEventReader(new FileReader(sourceFile)); while (reader.hasNext()) { final XMLEvent xmlEvent=reader.nextEvent(); if (xmlEvent.isStartElement() && isImportQName(xmlEvent.asStartElement().getName())) { processImportElement(xmlEvent.asStartElement(),writer,metadata); continue; } if (xmlEvent.isEndElement() && isImportQName(xmlEvent.asEndElement().getName())) continue; if (xmlEvent instanceof Comment) continue; if (xmlEvent.isCharacters()) if (xmlEvent.asCharacters().isWhiteSpace() || xmlEvent.asCharacters().isIgnorableWhiteSpace()) continue; writer.add(xmlEvent); if (xmlEvent.isStartDocument()) { writer.add(eventFactory.createComment("\nThis file is machine-generated. DO NOT MODIFY IT!\n")); } } storeFileModifications(metadata,metaDataFile); } finally { if (writer != null) try { writer.close(); } catch ( Exception ignored) { } if (reader != null) try { reader.close(); } catch ( Exception ignored) { } } }
Example 96
/** * Get the input source files to be used as input for the backup mappers * @param inputFs * @param inputPath * @param outputFs * @return * @throws IOException */ public Path[] createInputSources(List<Path> paths,FileSystem outputFs) throws IOException { int suggestedMapRedTasks=conf.getInt("mapred.map.tasks",1); Path[] inputSources=new Path[suggestedMapRedTasks]; for (int i=0; i < inputSources.length; i++) { inputSources[i]=new Path(NAME + "-inputsource" + i+ ".txt"); } List<BufferedWriter> writers=new ArrayList<BufferedWriter>(); int idx=0; try { for ( Path source : inputSources) { writers.add(new BufferedWriter(new OutputStreamWriter(outputFs.create(source)))); } for ( Path p : paths) { writers.get(idx).write(p.toString()); writers.get(idx).newLine(); idx++; if (idx >= inputSources.length) { idx=0; } } } finally { for ( BufferedWriter writer : writers) { checkAndClose(writer); } } return inputSources; }
Example 97
From project aksunai, under directory /src/org/androidnerds/app/aksunai/net/.
Source file: ConnectionThread.java

public void run(){ try { if (AppConstants.DEBUG) Log.d(AppConstants.NET_TAG,"Connecting to... " + mServerDetail.mUrl + ":"+ mServerDetail.mPort); mSock=new Socket(mServerDetail.mUrl,mServerDetail.mPort); } catch ( UnknownHostException e) { if (AppConstants.DEBUG) Log.d(AppConstants.NET_TAG,"UnknownHostException caught, terminating connection process"); } catch ( IOException e) { if (AppConstants.DEBUG) Log.d(AppConstants.NET_TAG,"IOException caught on socket creation. (Server) " + mServer + ", (Exception) "+ e.toString()); } try { mWriter=new BufferedWriter(new OutputStreamWriter(mSock.getOutputStream())); mReader=new BufferedReader(new InputStreamReader(mSock.getInputStream())); } catch ( IOException e) { if (AppConstants.DEBUG) Log.d(AppConstants.NET_TAG,"IOException caught grabbing input/output streams. (Server) " + mServer + ", (Exception) "+ e.toString()); } mServer.init(mServerDetail.mPass,mServerDetail.mNick,mServerDetail.mUser,mServerDetail.mRealName); try { while (!shouldKill()) { String message=mReader.readLine(); if (AppConstants.DEBUG) Log.d(AppConstants.NET_TAG,"Received message: " + message); mServer.receiveMessage(message); } } catch ( IOException e) { if (AppConstants.DEBUG) Log.d(AppConstants.NET_TAG,"IOException caught handling messages. (Server) " + mServer + ", (Exception) "+ e.toString()); } return; }
Example 98
From project arquillian-extension-persistence, under directory /impl/src/main/java/org/jboss/arquillian/persistence/core/client/.
Source file: DatabaseStateDumper.java

public void dump(@Observes DumpDataCommand dumpDataCommand){ final DataDump dataDump=dumpDataCommand.getDumpData(); Writer writer=null; try { writer=new BufferedWriter(new FileWriter(dataDump.getPath())); writer.write(dataDump.getDataSet()); } catch ( Exception e) { throw new DatabaseDumpException("Unable to dump database state to " + dataDump.getPath(),e); } finally { dumpDataCommand.setResult(true); if (writer != null) { try { writer.close(); } catch ( IOException e) { throw new DatabaseDumpException("Unable to close writer.",e); } } } }
Example 99
From project BioMAV, under directory /Behavior/src/nl/ru/ai/projects/parrot/tools/.
Source file: Writer.java

private void setupFile(){ File file; int counter=0; do { String tmpFilename=filename + "_" + counter+ ".txt"; file=new File(tmpFilename); counter++; } while (file.exists()); try { out=new BufferedWriter(new FileWriter(file)); } catch ( IOException ex) { System.err.println("Failed to open output-file"); } }
Example 100
From project BSPAN---Bluetooth-Sensor-Processing-for-Android, under directory /AndroidSpineExample/src/com/t2/androidspineexample/.
Source file: LogWriter.java

public void open(String fileName){ mFileName=fileName; try { File root=Environment.getExternalStorageDirectory(); if (root.canWrite()) { mLogFile=new File(root,fileName); mFileName=mLogFile.getAbsolutePath(); FileWriter gpxwriter=new FileWriter(mLogFile,true); mLogWriter=new BufferedWriter(gpxwriter); } else { Log.e(TAG,"Cannot write to log file"); AlertDialog.Builder alert=new AlertDialog.Builder(mContext); alert.setTitle("ERROR"); alert.setMessage("Cannot write to log file"); alert.setPositiveButton("Ok",new DialogInterface.OnClickListener(){ public void onClick( DialogInterface dialog, int whichButton){ } } ); alert.show(); } } catch ( IOException e) { Log.e(TAG,"Cannot write to log file" + e.getMessage()); AlertDialog.Builder alert=new AlertDialog.Builder(mContext); alert.setTitle("ERROR"); alert.setMessage("Cannot write to file"); alert.setPositiveButton("Ok",new DialogInterface.OnClickListener(){ public void onClick( DialogInterface dialog, int whichButton){ } } ); alert.show(); } }
Example 101
From project etherpad, under directory /infrastructure/net.appjet.common/util/.
Source file: LenientFormatter.java

/** * Constructs a {@code Formatter} with the given {@code Locale} and charset,and whose output is written to the specified {@code File}. * @param file the {@code File} that is used as the output destination for the{@code Formatter}. The {@code File} will be truncated to zero size if the {@code File}exists, or else a new {@code File} will be created. The output of the{@code Formatter} is buffered. * @param csn the name of the charset for the {@code Formatter}. * @param l the {@code Locale} of the {@code Formatter}. If {@code l} is {@code null}, then no localization will be used. * @throws FileNotFoundException if the {@code File} is not a normal and writable {@code File}, or if a new {@code File} cannot be created, or if any error rises when opening orcreating the {@code File}. * @throws SecurityException if there is a {@code SecurityManager} in place which denies permissionto write to the {@code File} in {@code checkWrite(file.getPath())}. * @throws UnsupportedEncodingException if the charset with the specified name is not supported. */ public LenientFormatter(File file,String csn,Locale l) throws FileNotFoundException, UnsupportedEncodingException { FileOutputStream fout=null; try { fout=new FileOutputStream(file); OutputStreamWriter writer=new OutputStreamWriter(fout,csn); out=new BufferedWriter(writer); } catch ( RuntimeException e) { closeOutputStream(fout); throw e; } catch ( UnsupportedEncodingException e) { closeOutputStream(fout); throw e; } locale=l; }
Example 102
From project activiti-explorer, under directory /src/main/java/org/activiti/explorer/servlet/.
Source file: ExplorerApplicationServlet.java

@Override protected void writeAjaxPageHtmlVaadinScripts(Window window,String themeName,Application application,BufferedWriter page,String appUrl,String themeUri,String appId,HttpServletRequest request) throws ServletException, IOException { super.writeAjaxPageHtmlVaadinScripts(window,themeName,application,page,appUrl,themeUri,appId,request); String scrollJs=themeUri + "/js/vscrollarea.js"; page.write("<script type=\"text/javascript\" src=\"" + scrollJs + "\" />"); String browserDependentCss="<script type=\"text/javascript\">//<![CDATA[" + "var mobi = ['opera', 'iemobile', 'webos', 'android', 'blackberry', 'ipad', 'safari'];" + "var midp = ['blackberry', 'symbian'];"+ "var ua = navigator.userAgent.toLowerCase();"+ "if ((ua.indexOf('midp') != -1) || (ua.indexOf('mobi') != -1) || ((ua.indexOf('ppc') != -1) && (ua.indexOf('mac') == -1)) || (ua.indexOf('webos') != -1)) {"+ " document.write('<link rel=\"stylesheet\" href=\"" + themeUri + "/allmobile.css\" type=\"text/css\" media=\"all\"/>');"+ " if (ua.indexOf('midp') != -1) {"+ " for (var i = 0; i < midp.length; i++) {"+ " if (ua.indexOf(midp[i]) != -1) {"+ " document.write('<link rel=\"stylesheet\" href=\""+ themeUri+ "' + midp[i] + '.css\" type=\"text/css\"/>');"+ " }"+ " }"+ " }"+ " else {"+ " if ((ua.indexOf('mobi') != -1) || (ua.indexOf('ppc') != -1) || (ua.indexOf('webos') != -1)) {"+ " for (var i = 0; i < mobi.length; i++) {"+ " if (ua.indexOf(mobi[i]) != -1) {"+ " if ((mobi[i].indexOf('blackberry') != -1) && (ua.indexOf('6.0') != -1)) {"+ " document.write('<link rel=\"stylesheet\" href=\""+ themeUri+ "' + mobi[i] + '6.0.css\" type=\"text/css\"/>');"+ " }"+ " else {"+ " document.write('<link rel=\"stylesheet\" href=\""+ themeUri+ "' + mobi[i] + '.css\" type=\"text/css\"/>');"+ " }"+ " break;"+ " }"+ " }"+ " }"+ " }"+ " }"+ "if ((navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('iPad') != -1)) {"+ " document.write('<meta name=\"viewport\" content=\"width=device-width\" />');"+ "}"+ " //]]>"+ "</script>"+ "<!--[if lt IE 7]><link rel=\"stylesheet\" type=\"text/css\" href=\""+ themeUri+ "/lt7.css\" /><![endif]-->"; page.write(browserDependentCss); }
Example 103
/** * @param fileName Where do you want to save your document ? * @return Returns true if nothing went wrong , false if the opposite is correct */ public boolean saveDocument(String fileName,JTextArea textarea){ boolean trueOrFalse=false; StringBuffer textBuffer=new StringBuffer(textarea.getText()); try { PrintWriter outFile=new PrintWriter(new BufferedWriter(new FileWriter(fileName))); outFile.print(textBuffer.toString() + "\n"); outFile.close(); trueOrFalse=true; } catch ( IOException e) { e.printStackTrace(); } return trueOrFalse; }
Example 104
From project droolsjbpm-integration, under directory /drools-camel/src/test/java/org/drools/camel/component/.
Source file: BatchTest.java

@Before public void before() throws Exception { tempReg.addNamedTemplate("tempReg",TemplateCompiler.compileTemplate(getClass().getResourceAsStream(dataformat + ".mvt"),(Map<String,Class<? extends Node>>)null)); TemplateRuntime.execute(tempReg.getNamedTemplate("tempReg"),null,tempReg); XMLUnit.setIgnoreComments(true); XMLUnit.setIgnoreWhitespace(true); XMLUnit.setIgnoreAttributeOrder(true); XMLUnit.setNormalizeWhitespace(true); XMLUnit.setNormalize(true); if (!StringUtils.isEmpty(copyToDataFormat)) { writer=new PrintWriter(new BufferedWriter(new FileWriter(copyToDataFormat + ".mvt",true))); } }
Example 105
From project EasySOA, under directory /samples/easysoa-samples-smarttravel/easysoa-samples-smarttravel-trip/src/main/java/fr/inria/galaxy/j1/scenario1/.
Source file: SummaryServiceBadQoS.java

private void saveResult(String city,String country,String meteo,double exchangeRate,String chosenPhrase,String translatedPhrase){ File f=new File(FILE_PREFIX + new Date().getTime()); try { PrintWriter out=new PrintWriter(new BufferedWriter(new FileWriter(f))); out.append("City: " + city + NEW_LINE); out.append("Country: " + country + NEW_LINE); out.append("Meteo: " + meteo + NEW_LINE); out.append("Exchange rate: " + exchangeRate + NEW_LINE); out.append("Chosen phrase: " + chosenPhrase + NEW_LINE); out.append("Translated phrase: " + chosenPhrase + NEW_LINE); out.flush(); out.close(); } catch ( IOException e) { e.printStackTrace(); } }
Example 106
From project encog-java-workbench, under directory /src/main/java/org/encog/workbench/util/.
Source file: JavaClassPathUtil.java

public static void main(final String args[]){ if (args.length != 1) { System.out.println("Please pass the workbench directory as arg 1"); } else { try { final File baseDir=new File(args[0]); final File jarDir=new File(baseDir,"jar"); final StringBuilder batCommand=new StringBuilder(); batCommand.append("start javaw -classpath "); batCommand.append(JavaClassPathUtil.generateClassPath(';',jarDir)); batCommand.append(" org.encog.workbench.EncogWorkBench"); PrintWriter out=new PrintWriter(new BufferedWriter(new FileWriter(new File(baseDir,"workbench.bat")))); out.println(batCommand); out.close(); final StringBuilder shCommand=new StringBuilder(); shCommand.append("java -classpath "); shCommand.append(JavaClassPathUtil.generateClassPath(':',jarDir)); shCommand.append(" org.encog.workbench.EncogWorkBench"); out=new PrintWriter(new BufferedWriter(new FileWriter(new File(baseDir,"workbench.sh")))); out.println(shCommand); out.close(); } catch ( final Exception e) { e.printStackTrace(); } } }