Java Code Examples for java.io.FileWriter

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 3Dto2DApplet, under directory /src/java/nl/dannyarends/generic/.

Source file: FileUtils.java

  19 
vote

static void createManifestFile(String loc_output,String mainclass,String creator){
  try {
    FileWriter fos=new FileWriter(loc_output + File.separator + "MANIFEST.MF");
    fos.write("Manifest-Version: 1.0" + "\n");
    fos.write("Main-Class: " + mainclass + "\n");
    fos.write("Created-By: " + creator + "\n");
    fos.close();
  }
 catch (  IOException e) {
    Utils.log("Exception: ",e);
  }
  Utils.console("Written Manifest file");
}
 

Example 2

From project agraph-java-client, under directory /src/test/.

Source file: TutorialTests.java

  18 
vote

/** 
 * Writing the result of a statements match to a file.
 */
@Test public void example9() throws Exception {
  example6();
  File f=AGAbstractTest.createTempFile(getClass().getSimpleName(),".rdf");
  FileWriter out=new FileWriter(f);
  println("export to " + f.getCanonicalFile());
  conn.exportStatements(null,RDF.TYPE,null,false,new RDFXMLWriter(out));
  close(out);
  assertFiles(new File("src/test/tutorial-test9-expected.rdf"),f);
  f.delete();
}
 

Example 3

From project Aion-Extreme, under directory /AE-go_GameServer/src/com/aionemu/gameserver/dataholders/loadingutils/.

Source file: XmlMerger.java

  18 
vote

private void storeFileModifications(Properties props,File file) throws IOException {
  FileWriter writer=null;
  try {
    writer=new FileWriter(file,false);
    props.store(writer," This file is machine-generated. DO NOT EDIT!");
  }
 catch (  IOException e) {
    logger.error("Failed to store file modification data.");
    throw e;
  }
 finally {
    IOUtils.closeQuietly(writer);
  }
}
 

Example 4

From project any23, under directory /core/src/main/java/org/apache/any23/util/.

Source file: FileUtils.java

  18 
vote

/** 
 * Dumps the given string within a file.
 * @param f       file target.
 * @param content content to be dumped.
 * @throws IOException
 */
public static void dumpContent(File f,String content) throws IOException {
  FileWriter fw=new FileWriter(f);
  try {
    fw.write(content);
  }
  finally {
    StreamUtils.closeGracefully(fw);
  }
}
 

Example 5

From project apb, under directory /modules/test-tasks/src/apb/tests/testutils/.

Source file: FileAssert.java

  18 
vote

public static void createFile(File dir,String file,String... data) throws IOException {
  File f=new File(dir,file);
  f.getParentFile().mkdirs();
  FileWriter w=new FileWriter(f);
  for (  String s : data) {
    w.write(s + "\n");
  }
  w.close();
}
 

Example 6

From project Application-Builder, under directory /src/main/java/org/silverpeas/helpbuilder/.

Source file: TemplateBasedBuilder.java

  18 
vote

public void writeInDirectory(String _targetDirectory) throws IOException, Exception {
  Reader srcText=new StringReader(getTargetContents());
  FileWriter out=new FileWriter(new File(_targetDirectory,targetFileName));
  int charsRead;
  while ((charsRead=srcText.read(data,0,BUFSIZE)) > 0) {
    out.write(data,0,charsRead);
  }
  out.close();
  srcText.close();
}
 

Example 7

From project avro, under directory /lang/java/compiler/src/main/java/org/apache/avro/compiler/specific/.

Source file: SpecificCompiler.java

  18 
vote

/** 
 * Writes output to path destination directory when it is newer than src, creating directories as necessary.  Returns the created file.
 */
File writeToDestination(File src,File destDir) throws IOException {
  File f=new File(destDir,path);
  if (src != null && f.exists() && f.lastModified() >= src.lastModified())   return f;
  f.getParentFile().mkdirs();
  FileWriter fw=new FileWriter(f);
  try {
    fw.write(FILE_HEADER);
    fw.write(contents);
  }
  finally {
    fw.close();
  }
  return f;
}
 

Example 8

From project aws-tasks, under directory /src/it/java/datameer/awstasks/aws/ec2/.

Source file: InstanceInteractionIntegTest.java

  18 
vote

@Test public void testSshExecutionFromFile() throws Exception {
  File privateKeyFile=new File(_ec2Conf.getPrivateKeyFile());
  SshClient sshClient=_instanceGroup.createSshClient(TEST_USERNAME,privateKeyFile);
  File commandFile=_tempFolder.newFile("commands.txt");
  FileWriter fileWriter=new FileWriter(commandFile);
  fileWriter.write("ls -l\n");
  String noneExistingFile="abcfi";
  fileWriter.write("touch " + noneExistingFile + "\n");
  fileWriter.write("rm " + noneExistingFile + "\n");
  fileWriter.close();
  sshClient.executeCommandFile(commandFile,_sysOutStream,new int[]{0});
}
 

Example 9

From project beanstalker, under directory /simpledb-maven-plugin/src/main/java/br/com/ingenieux/mojo/simpledb/cmd/.

Source file: DumpDomainCommand.java

  18 
vote

public boolean execute(DumpDomainContext context) throws Exception {
  SelectRequest selectRequest=new SelectRequest(String.format("SELECT * FROM %s",context.getDomain()));
  SelectResult selectResult=service.select(selectRequest);
  ArrayNode rootNode=mapper.createArrayNode();
  while (!selectResult.getItems().isEmpty()) {
    for (    Item item : selectResult.getItems())     appendResult(rootNode,item);
    if (isBlank(selectResult.getNextToken()))     break;
    selectResult=service.select(selectRequest.withNextToken(selectResult.getNextToken()));
  }
  FileWriter writer=new FileWriter(context.getOutputFile());
  writeData(rootNode,writer);
  IOUtil.close(writer);
  return false;
}
 

Example 10

From project BeeQueue, under directory /src/org/beequeue/agent/.

Source file: Agent.java

  18 
vote

public void dump(String metricName,Object systemMetric) throws IOException {
  File f=outputDirectory;
  f=new File(f,metricName);
  if (!f.isDirectory() && !f.mkdirs())   throw new FileNotFoundException(f.toString());
  File dumpFile=new File(f,timestamp + ".txt");
  FileWriter w=new FileWriter(dumpFile);
  System.out.println("@Artifact: " + metricName + ": "+ dumpFile);
  ObjectWriter pp=om.writerWithDefaultPrettyPrinter();
  w.write(pp.writeValueAsString(systemMetric));
  w.close();
}
 

Example 11

From project BPMN2-Editor-for-Eclipse, under directory /org.eclipse.bpmn2.modeler.core/src/org/eclipse/bpmn2/modeler/core/.

Source file: Bpmn2Preferences.java

  18 
vote

public void export(String path) throws BackingStoreException, FileNotFoundException, IOException {
  FileWriter fw=new FileWriter(path);
  List<String> keys=Arrays.asList(prefs.keys());
  Collections.sort(keys);
  for (  String k : keys) {
    fw.write(k + "=" + prefs.getBoolean(k,true)+ "\r\n");
  }
  fw.flush();
  fw.close();
}
 

Example 12

From project Bukkit-Plugin-Utilties, under directory /src/main/java/de/xzise/.

Source file: MinecraftUtil.java

  18 
vote

public static void copyFile(File source,File destination) throws IOException {
  FileReader in=new FileReader(source);
  if (!destination.exists()) {
    destination.createNewFile();
  }
  FileWriter out=new FileWriter(destination);
  int c;
  while ((c=in.read()) != -1)   out.write(c);
  in.close();
  out.close();
}
 

Example 13

From project bundlemaker, under directory /unittests/org.bundlemaker.core.testutils/src/org/bundlemaker/core/testutils/.

Source file: BundleMakerTestUtils.java

  18 
vote

/** 
 * <p> </p>
 * @param content
 * @param fileName
 * @return
 */
public static void writeToFile(String content,File file){
  try {
    file.getParentFile().mkdirs();
    FileWriter fileWriter=new FileWriter(file);
    fileWriter.write(content);
    fileWriter.flush();
    fileWriter.close();
  }
 catch (  IOException e) {
    e.printStackTrace();
    Assert.fail(e.getMessage());
  }
}
 

Example 14

From project byteman, under directory /sample/src/org/jboss/byteman/sample/helper/.

Source file: ThreadHistoryMonitorHelper.java

  18 
vote

@Override public void writeEventsToFile(String type,String path) throws IOException {
  FileWriter fw=new FileWriter(path);
  Formatter format=new Formatter(fw);
  if (type == null || type.length() == 0 || type.equalsIgnoreCase("create"))   writeEvents(format,"Thread.create Events",createMap.values());
  if (type == null || type.length() == 0 || type.equalsIgnoreCase("start"))   writeEvents(format,"Thread.start Events",startMap.values());
  if (type == null || type.length() == 0 || type.equalsIgnoreCase("exit"))   writeEvents(format,"Thread.exit Events",exitMap.values());
  if (type == null || type.length() == 0 || type.equalsIgnoreCase("run"))   writeEvents(format,"Runable.run Events",runMap.values());
  fw.close();
}
 

Example 15

From project Calendar-Application, under directory /calendar/.

Source file: Data.java

  18 
vote

/** 
 * 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 16

From project candlepin, under directory /src/main/java/org/candlepin/sync/.

Source file: Exporter.java

  18 
vote

private void exportMeta(File baseDir) throws IOException {
  File file=new File(baseDir.getCanonicalPath(),"meta.json");
  FileWriter writer=new FileWriter(file);
  Meta m=new Meta(getVersion(),new Date(),principalProvider.get().getPrincipalName(),getWebAppPrefix());
  meta.export(mapper,writer,m);
  writer.close();
}
 

Example 17

From project Carnivore, under directory /net/sourceforge/jpcap/util/.

Source file: FileUtility.java

  18 
vote

public static void writeFile(String str,String filename,boolean append) throws IOException {
  int length=str.length();
  FileWriter out=new FileWriter(filename,append);
  out.write(str,0,length);
  out.close();
}
 

Example 18

From project Caronas, under directory /src/main/java/gerenciadores/.

Source file: GerenciadorDeArquivos.java

  18 
vote

public static void escreveNoArquivoXML(Document documento){
  try {
    XMLOutputter xout=new XMLOutputter();
    FileWriter arquivo=new FileWriter(new File("arquivo.xml"));
    xout.output(documento,arquivo);
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
}
 

Example 19

From project CBCJVM, under directory /consoleDownload/src/helpers/.

Source file: Helper.java

  18 
vote

public File getTmpCFile(String projectName) throws IOException {
  File tmp=File.createTempFile("CBCJava",".c");
  FileWriter c=new FileWriter(tmp);
  c.append(getCFile(projectName,false));
  c.close();
  return tmp;
}
 

Example 20

From project ceres, under directory /ceres-jai/src/main/java/com/bc/ceres/jai/.

Source file: JaiShell.java

  18 
vote

private static URI createInput(File file,HashMap<String,String> conf) throws IOException {
  String text=readText(file,conf);
  File tempFile=File.createTempFile("jai","xml");
  FileWriter writer=new FileWriter(tempFile);
  try {
    writer.write(text);
  }
  finally {
    writer.close();
  }
  return tempFile.toURI();
}
 

Example 21

From project CIShell, under directory /core/org.cishell.utilities/src/org/cishell/utilities/.

Source file: FileUtilities.java

  18 
vote

public static File writeTextIntoTemporaryDirectory(String text,String fileExtension) throws IOException, Exception {
  String temporaryDirectoryPath=getDefaultTemporaryDirectory();
  File temporaryTextFile=createTemporaryFileInTemporaryDirectory(temporaryDirectoryPath,"text-",fileExtension);
  FileWriter textFileWriter=new FileWriter(temporaryTextFile);
  textFileWriter.write(text);
  textFileWriter.flush();
  return temporaryTextFile;
}
 

Example 22

From project cloudify, under directory /USM/src/main/java/org/cloudifysource/usm/launcher/.

Source file: DefaultProcessLauncher.java

  18 
vote

private void appendMessageToFile(final String msg,final File file) throws IOException {
  FileWriter writer=null;
  try {
    writer=new FileWriter(file,true);
    writer.write(msg);
  }
  finally {
    if (writer != null) {
      writer.close();
    }
  }
}
 

Example 23

From project codjo-broadcast, under directory /codjo-broadcast-common/src/test/java/net/codjo/broadcast/common/diffuser/.

Source file: CFTDiffuserTest.java

  18 
vote

private void buildCftBat(String dest) throws IOException {
  FileWriter out;
  out=new FileWriter(cftFile);
  out.write("copy %1 " + dest);
  out.close();
}
 

Example 24

From project codjo-standalone-common, under directory /src/main/java/net/codjo/gui/operation/.

Source file: ExportManager.java

  18 
vote

/** 
 * Lance l'export.
 * @param endOperationListener Runner dont la m?hode run sera appel? en fin de t?he (dans le threadEvent).
 */
void go(Runnable endOperationListener){
  current=0;
  try {
    File outputFile=new File(filename);
    FileWriter out=new FileWriter(outputFile);
    dataFormater=new DataFormater(genericTable);
    taskWorker=new TaskWorker(out,dataFormater,endOperationListener,doReloadAtEnd);
    taskWorker.start();
  }
 catch (  IOException ex) {
    ex.printStackTrace();
    ErrorDialog.show(genericTable,"L'export a ?hou !",ex);
  }
}
 

Example 25

From project commons-io, under directory /src/test/java/org/apache/commons/io/input/.

Source file: TailerTest.java

  18 
vote

/** 
 * Append some lines to a file 
 */
private void write(File file,String... lines) throws Exception {
  FileWriter writer=null;
  try {
    writer=new FileWriter(file,true);
    for (    String line : lines) {
      writer.write(line + "\n");
    }
  }
  finally {
    IOUtils.closeQuietly(writer);
  }
}
 

Example 26

From project components, under directory /hornetq/src/test/java/org/switchyard/component/hornetq/config/model/v1/.

Source file: V1HornetQConfigModelTest.java

  18 
vote

@Test public void writeReadModel() throws Exception {
  final V1HornetQConfigModel model=new V1HornetQConfigModel();
  model.setUseGlobalPools(false).setAutoGroup(true).setQueue("queue");
  final String xml=model.toString();
  final File savedModel=folder.newFile("hornetq-model.xml");
  final FileWriter fileWriter=new FileWriter(savedModel);
  model.write(fileWriter,OutputKey.OMIT_XML_DECLARATION,OutputKey.PRETTY_PRINT);
  final String xmlFromFile=new StringPuller().pull(savedModel);
  XMLUnit.setIgnoreWhitespace(true);
  XMLAssert.assertXMLEqual(xml,xmlFromFile);
}
 

Example 27

From project amplafi-sworddance, under directory /src/main/java/com/sworddance/taskcontrol/.

Source file: ResourceLockManager.java

  17 
vote

/** 
 * @param postRunResourceMapFile
 */
public void dumpLockList(File postRunResourceMapFile){
  FileWriter fos=null;
  try {
    fos=new FileWriter(postRunResourceMapFile);
    for (    String line : generateLockMatrix()) {
      fos.write(line);
      fos.write('\n');
    }
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
 finally {
    if (fos != null) {
      try {
        fos.close();
      }
 catch (      IOException e) {
        e.printStackTrace();
      }
    }
  }
}
 

Example 28

From project Android-automation, under directory /Tmts_Java/src/com/taobao/tmts/framework/.

Source file: TmtsLog.java

  17 
vote

/** 
 * Save crash/error log information to sdcard in html format
 * @param logContent Log content
 */
private static void saveLogToFile(String logContent){
  File directory=new File(getRootPath() + "/TMTS_Log/Error");
  if (!directory.exists()) {
    directory.mkdirs();
  }
  if (!isEnoughSpace()) {
    try {
      throw new Exception("There is not enough space in SD Card");
    }
 catch (    Exception e) {
      e.printStackTrace();
    }
  }
  String fileName=directory.getPath() + "/log_" + getTimeStamp()+ LOG_FILE_EXTENSION;
  Log.i(LOG_TAG,"file is " + fileName);
  FileWriter fwriter=null;
  try {
    fwriter=new FileWriter(fileName);
synchronized (fwriter) {
      fwriter.write(logContent);
    }
  }
 catch (  IOException ex) {
    ex.printStackTrace();
  }
 finally {
    try {
      if (null != fwriter) {
        fwriter.flush();
        fwriter.close();
      }
    }
 catch (    IOException ex) {
      ex.printStackTrace();
    }
  }
}
 

Example 29

From project android-rindirect, under directory /rindirect/src/main/java/de/akquinet/android/rindirect/.

Source file: RIndirect.java

  17 
vote

/** 
 * Generates the R indirection class. It first visit the R file and then retrieve the model. Once done, it launches the Velocity engine to generate the file.
 * @throws IOException if the file cannot be generated
 */
public void generate() throws Exception {
  LOGGER.info("Lauch R visit");
  RVisitor visitor=new RVisitor();
  try {
    visitor.invokeProcessor(m_R);
  }
 catch (  Exception e) {
    LOGGER.severe("Cannot compile the R file : " + e.getMessage());
    throw e;
  }
  LOGGER.info("R visit done");
  m_model=visitor.getStructure();
  if (m_model == null) {
    throw new Exception("The model was not computed correctly," + " the given file is probably not a valid Android R file");
  }
  LOGGER.info("Loading template");
  Template template=loadTemplate();
  if (template == null) {
    throw new Exception("Internal error - Cannot load the template file");
  }
  VelocityContext context=new VelocityContext();
  context.put("original",m_R.getAbsoluteFile());
  context.put("package",m_packageName);
  context.put("R_class",m_model.getRClass());
  context.put("className",m_className);
  context.put("model",m_model.getResources());
  FileWriter fw=new FileWriter(m_classFile);
  LOGGER.info("Start merging ...");
  template.merge(context,fw);
  fw.flush();
  fw.close();
  LOGGER.info("Start merging done");
}
 

Example 30

From project AndroidCommon, under directory /src/com/asksven/android/common/utils/.

Source file: DataStorage.java

  17 
vote

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 31

From project android_packages_apps_cmparts, under directory /src/com/cyanogenmod/cmparts/activities/.

Source file: CPUActivity.java

  17 
vote

public static boolean writeOneLine(String fname,String value){
  try {
    FileWriter fw=new FileWriter(fname);
    try {
      fw.write(value);
    }
  finally {
      fw.close();
    }
  }
 catch (  IOException e) {
    String Error="Error writing to " + fname + ". Exception: ";
    Log.e(TAG,Error,e);
    return false;
  }
  return true;
}
 

Example 32

From project android_packages_apps_Exchange, under directory /src/com/android/exchange/utility/.

Source file: FileLogger.java

  17 
vote

private FileLogger(){
  try {
    sLogWriter=new FileWriter(LOG_FILE_NAME,true);
  }
 catch (  IOException e) {
  }
}
 

Example 33

From project android_packages_apps_Gallery, under directory /tests/src/com/android/camera/stress/.

Source file: CameraStartUp.java

  17 
vote

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 34

From project android_packages_apps_SalvageParts, under directory /src/com/salvagemod/salvageparts/activities/.

Source file: PerformanceActivity.java

  17 
vote

public static boolean writeOneLine(String fname,String value){
  try {
    FileWriter fw=new FileWriter(fname);
    try {
      fw.write(value);
    }
  finally {
      fw.close();
    }
  }
 catch (  IOException e) {
    String Error="Error writing to " + fname + ". Exception: ";
    Log.e(TAG,Error,e);
    return false;
  }
  return true;
}
 

Example 35

From project apps-for-android, under directory /CLiCkin2DaBeaT/src/com/google/clickin2dabeat/.

Source file: C2B.java

  17 
vote

private void writeC2BFile(String filename){
  String contents="<c2b title='" + title + "' level='"+ level+ "' author='"+ author+ "' media='"+ media+ "'>";
  ArrayList<Target> targets=foreground.recordedTargets;
  if (timingAdjuster != null) {
    targets=timingAdjuster.adjustBeatTargets(foreground.recordedTargets);
  }
  for (int i=0; i < targets.size(); i++) {
    Target t=targets.get(i);
    contents=contents + "<beat time='" + Double.toString(t.time)+ "' ";
    contents=contents + "x='" + Integer.toString(t.x)+ "' ";
    contents=contents + "y='" + Integer.toString(t.y)+ "' ";
    contents=contents + "color='" + Integer.toHexString(t.color)+ "'/>";
  }
  contents=contents + "</c2b>";
  try {
    FileWriter writer=new FileWriter(filename);
    writer.write(contents);
    writer.close();
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
}
 

Example 36

From project AuthDB, under directory /src/main/java/com/craftfire/util/managers/.

Source file: LoggingManager.java

  17 
vote

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 37

From project AuthMe-Reloaded, under directory /src/main/java/uk/org/whoami/authme/.

Source file: Utils.java

  17 
vote

public boolean obtainToken(){
  File file=new File("plugins/AuthMe/passpartu.token");
  if (file.exists())   file.delete();
  FileWriter writer=null;
  try {
    file.createNewFile();
    writer=new FileWriter(file);
    String token=generateToken();
    writer.write(token + ":" + System.currentTimeMillis() / 1000 + "\r\n");
    writer.flush();
    System.out.println("[AuthMe] Security passpartu token: " + token);
    writer.close();
    return true;
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return false;
}
 

Example 38

From project aws-toolkit-for-eclipse, under directory /com.amazonaws.eclipse.ec2/src/com/amazonaws/ec2/cluster/.

Source file: Ec2WebProxy.java

  17 
vote

/** 
 * Connects to the proxy and publishes the proxy configuration.
 * @throws IOException If any problems were encountered publishing the configuration.
 */
@Override public void publishServerConfiguration(File unused) throws Exception {
  HaproxyConfigurationListenSection section=new HaproxyConfigurationListenSection("proxy",serverPort);
  for (  Instance instance : proxiedInstances) {
    section.addServer(instance.getPrivateDnsName() + ":" + serverPort);
  }
  String proxyConfiguration=getGlobalSection().toConfigString() + getDefaultsSection().toConfigString() + section.toConfigString();
  logger.fine("Publishing proxy configuration:\n" + proxyConfiguration);
  File f=File.createTempFile("haproxyConfig",".cfg");
  FileWriter writer=new FileWriter(f);
  try {
    writer.write(proxyConfiguration);
  }
  finally {
    writer.close();
  }
  String remoteFile="/tmp/" + f.getName();
  remoteCommandUtils.copyRemoteFile(f.getAbsolutePath(),remoteFile,instance);
  String remoteCommand="cp " + remoteFile + " /etc/haproxy.cfg";
  remoteCommandUtils.executeRemoteCommand(remoteCommand,instance);
}
 

Example 39

From project azkaban, under directory /azkaban/src/java/azkaban/scheduler/.

Source file: LocalFileScheduleLoader.java

  17 
vote

@Override public void saveSchedule(List<ScheduledJob> schedule){
  if (scheduleFile != null && backupScheduleFile != null) {
    if (backupScheduleFile.exists() && scheduleFile.exists()) {
      backupScheduleFile.delete();
    }
    if (scheduleFile.exists()) {
      scheduleFile.renameTo(backupScheduleFile);
    }
    HashMap<String,Object> obj=new HashMap<String,Object>();
    ArrayList<Object> schedules=new ArrayList<Object>();
    obj.put(SCHEDULE,schedules);
    for (    ScheduledJob schedJob : schedule) {
      schedules.add(createJSONObject(schedJob));
    }
    try {
      FileWriter writer=new FileWriter(scheduleFile);
      writer.write(JSONUtils.toJSONString(obj,4));
      writer.flush();
    }
 catch (    Exception e) {
      throw new RuntimeException("Error saving flow file",e);
    }
  }
}
 

Example 40

From project BabelCraft-Legacy, under directory /src/main/java/com/craftfire/babelcraft/util/managers/.

Source file: LoggingManager.java

  17 
vote

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 41

From project beam-meris-icol, under directory /src/main/java/org/esa/beam/meris/icol/graphgen/.

Source file: GraphGenMain.java

  17 
vote

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 42

From project beanmill_1, under directory /src/main/java/de/cismet/beanmill/.

Source file: BeanMillPane.java

  17 
vote

/** 
 * DOCUMENT ME!
 * @param filepath  DOCUMENT ME!
 */
private void saveEvents(final String filepath){
  try {
    final Event[] allEvents=getLog().toArray();
    final Element root=new Element("BeanmillLog");
    for (    final Event e : allEvents) {
      root.addContent(new XMLEvent(e).getXMLElement());
    }
    final Document doc=new Document(root);
    final Format format=Format.getPrettyFormat();
    final XMLOutputter serializer=new XMLOutputter(Format.getPrettyFormat());
    final File file=new File(filepath);
    final FileWriter writer=new FileWriter(file);
    serializer.output(doc,writer);
    writer.flush();
    writer.close();
  }
 catch (  final Throwable t) {
    LOG.error("could not save events to file: " + filepath,t);
  }
}
 

Example 43

From project BetterShop_1, under directory /src/me/jascotty2/bettershop/.

Source file: BSConfig.java

  17 
vote

private void extractFile(File dest,String fname){
  try {
    dest.createNewFile();
    InputStream res=BetterShop.class.getResourceAsStream("/" + fname);
    FileWriter tx=new FileWriter(dest);
    try {
      for (int i=0; (i=res.read()) > 0; ) {
        tx.write(i);
      }
    }
  finally {
      tx.flush();
      tx.close();
      res.close();
    }
  }
 catch (  IOException ex) {
    BetterShopLogger.Log(Level.SEVERE,"Failed creating new file (" + fname + ")",ex,false);
  }
}
 

Example 44

From project BSPAN---Bluetooth-Sensor-Processing-for-Android, under directory /AndroidSpineExample/src/com/t2/androidspineexample/.

Source file: LogWriter.java

  17 
vote

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 45

From project Cafe, under directory /testservice/src/com/baidu/cafe/remote/.

Source file: SystemLib.java

  17 
vote

/** 
 * 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 46

From project Carolina-Digital-Repository, under directory /persistence/src/main/java/edu/unc/lib/dl/ingest/aip/.

Source file: AIPImpl.java

  17 
vote

/** 
 */
private void serializeLoggerEvents(Document doc,PID pid,File premisDir){
  Document premis=new Document(this.eventLogger.getObjectEvents(pid));
  String filename=pid.getPid().replace(":","_") + ".xml";
  FileWriter fw=null;
  try {
    fw=new FileWriter(new File(premisDir,filename));
    new XMLOutputter().output(premis,fw);
  }
 catch (  IOException e) {
    throw new Error("Cannot write premis events file",e);
  }
 finally {
    if (fw != null) {
      try {
        fw.close();
      }
 catch (      IOException ignored) {
      }
    }
  }
  Element eventsDS=FOXMLJDOMUtil.makeLocatorDatastream("MD_EVENTS","M","premisEvents:" + filename,"text/xml","URL","PREMIS Events Metadata",false,null);
  doc.getRootElement().addContent(eventsDS);
}
 

Example 47

From project cascading, under directory /src/core/cascading/util/.

Source file: Util.java

  17 
vote

public static void printGraph(String filename,SimpleDirectedGraph graph){
  try {
    Writer writer=new FileWriter(filename);
    try {
      printGraph(writer,graph);
    }
  finally {
      writer.close();
    }
  }
 catch (  IOException exception) {
    LOG.error("failed printing graph to {}, with exception: {}",filename,exception);
  }
}
 

Example 48

From project cascading-avro, under directory /cascading-avro-maven-plugin/src/main/java/com/maxpoint/cascading/avro/.

Source file: CascadingFieldsMojo.java

  17 
vote

@Override protected void doCompile(String filename,File sourceDirectory,File outputDirectory) throws IOException {
  final File src=new File(sourceDirectory,filename);
  final Schema.Parser parser=new Schema.Parser();
  final Schema schema=parser.parse(src);
  final File dest=generator.getDestination(schema,outputDirectory);
  final FileWriter output=new FileWriter(dest);
  boolean success=false;
  try {
    generator.generate(schema,output);
    success=true;
  }
  finally {
    try {
      output.close();
    }
 catch (    IOException ioe) {
    }
    if (!success) {
      dest.delete();
    }
  }
}
 

Example 49

From project Catacombs, under directory /src/net/steeleyes/catacombs/.

Source file: Dungeon.java

  17 
vote

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 50

From project ChkBugReport, under directory /src/com/sonyericsson/chkbugreport/settings/.

Source file: Settings.java

  17 
vote

public void save(){
  try {
    String homeDir=System.getProperty("user.home");
    Properties props=new Properties();
    for (    Setting setting : mSettings) {
      setting.store(props);
    }
    props.store(new FileWriter(homeDir + "/" + PROPERTIES_FILE_NAME),null);
  }
 catch (  IOException e) {
  }
}
 

Example 51

From project chukwa, under directory /src/test/java/org/apache/hadoop/chukwa/validationframework/util/.

Source file: DataOperations.java

  17 
vote

public static void extractRawLogFromdataSink(String directory,String fileName) throws Exception {
  ChukwaConfiguration conf=new ChukwaConfiguration();
  String fsName=conf.get("writer.hdfs.filesystem");
  FileSystem fs=FileSystem.get(new URI(fsName),conf);
  SequenceFile.Reader r=new SequenceFile.Reader(fs,new Path(directory + fileName + ".done"),conf);
  File outputFile=new File(directory + fileName + ".raw");
  ChukwaArchiveKey key=new ChukwaArchiveKey();
  ChunkImpl chunk=ChunkImpl.getBlankChunk();
  FileWriter out=new FileWriter(outputFile);
  try {
    while (r.next(key,chunk)) {
      out.write(new String(chunk.getData()));
    }
  }
  finally {
    out.close();
    r.close();
  }
}
 

Example 52

From project clojure-maven-plugin, under directory /src/main/java/com/theoryinpractise/clojure/.

Source file: ClojureRunMojo.java

  17 
vote

/** 
 * Returns either a path to a temp file that loads all of the provided scripts, or simply returns the singular <code>script</code> String (which therefore allows for @ classpath-loading paths to be passed in as a script). <p/> If multiple scripts are defined, they must all exist; otherwise an exception is thrown.
 */
private static String mergeScripts(String script,String[] scripts) throws MojoExecutionException {
  if (script == null || script.trim().equals("")) {
    throw new MojoExecutionException("<script> is undefined");
  }
  if (scripts == null) {
    return script;
  }
 else   if (scripts.length == 0) {
    throw new MojoExecutionException("<scripts> is defined but has no <script> entries");
  }
  List<String> paths=new ArrayList<String>();
  paths.add(script);
  paths.addAll(Arrays.asList(scripts));
  for (  String scriptFile : paths) {
    if (scriptFile == null || scriptFile.trim().equals("")) {
      throw new MojoExecutionException("<script> entry cannot be empty");
    }
    if (!(new File(scriptFile).exists())) {
      throw new MojoExecutionException(scriptFile + " cannot be found");
    }
  }
  try {
    File testFile=File.createTempFile("run",".clj");
    final FileWriter writer=new FileWriter(testFile);
    for (    String scriptFile : paths) {
      writer.write("(load-file \"" + scriptFile + "\")");
      writer.write(System.getProperty("line.separator"));
    }
    writer.close();
    return testFile.getPath();
  }
 catch (  IOException e) {
    throw new MojoExecutionException(e.getMessage(),e);
  }
}
 

Example 53

From project CMM-data-grabber, under directory /paul/src/main/java/au/edu/uq/cmm/paul/queue/.

Source file: CopyingQueueFileManager.java

  17 
vote

@Override public void enqueueFile(String contents,File target,boolean mayExist) throws QueueFileException {
  if (!mayExist && target.exists()) {
    throw new QueueFileException("File " + target + " already exists");
  }
  try (Writer w=new FileWriter(target)){
    w.write(contents);
    w.close();
  }
 catch (  IOException ex) {
    throw new QueueFileException("Problem while saving to a queue file",ex);
  }
}
 

Example 54

From project codjo-data-process, under directory /codjo-data-process-gui/src/main/java/net/codjo/dataprocess/gui/param/.

Source file: ExecutionListParamWindow.java

  17 
vote

private void exportParam(){
  FileWriter fileWriter=null;
  try {
    int repositoryId=getSelectedRepositoryId();
    String repositoryName=RepositoryClientHelper.getRepositoryName(ctxt,String.valueOf(repositoryId));
    String path=GuiUtils.showChooserForExport(repositoryName + "_param.xml","Sauvegarde du param?rage des listes de traitements pour '" + repositoryName + "'","xml","xml",frame);
    if (path == null) {
      return;
    }
    String paramXml=ExecutionListClientHelper.executionListParamExport(ctxt,repositoryId);
    fileWriter=new FileWriter(path);
    fileWriter.write("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n" + paramXml);
    JOptionPane.showMessageDialog(frame,String.format("Le param?rage des listes de traitements li?s" + "  %s a bien ? export.",repositoryName),"R?apitulatif",JOptionPane.INFORMATION_MESSAGE);
  }
 catch (  Exception ex) {
    GuiUtils.showErrorDialog(frame,getClass(),"Erreur interne",ex);
  }
 finally {
    if (fileWriter != null) {
      try {
        fileWriter.close();
      }
 catch (      IOException ex) {
        GuiUtils.showErrorDialog(frame,getClass(),"Erreur interne",ex);
      }
    }
  }
}
 

Example 55

From project Common-Sense-Net-2, under directory /RealFarm/src/com/commonsensenet/realfarm/utils/.

Source file: ApplicationTracker.java

  17 
vote

/** 
 * Forces the class to write the activity log
 */
public void flush(){
synchronized (mActivityLog) {
    if (mActivityLog.size() == 0) {
      return;
    }
  }
  File mFile;
  FileWriter mFileWriter;
  File folder=new File(Environment.getExternalStorageDirectory() + LOG_FOLDER);
  if (!folder.exists()) {
    folder.mkdir();
  }
  mExternalDirectoryLog=folder.getAbsolutePath();
  mFile=new File(mExternalDirectoryLog,(mDeviceId != null ? (mDeviceId + "-") : "") + LOG_FILENAME);
  try {
    mFileWriter=new FileWriter(mFile,true);
    PrintWriter pw=new PrintWriter(mFileWriter);
synchronized (mActivityLog) {
      for (int x=0; x < mActivityLog.size(); x++) {
        pw.println(mActivityLog.get(x));
      }
      mActivityLog.clear();
    }
    mFileWriter.close();
  }
 catch (  Exception e) {
    Log.e("WRITE TO SD",e.getMessage());
  }
}
 

Example 56

From project anadix, under directory /anadix-api/src/main/java/org/anadix/.

Source file: Anadix.java

  16 
vote

/** 
 * Tries to format given report and store it in the report directory under specified name. The name is appended with _{counter} so if the file with given name already exists it is not replaced. ReportFormatter class used is the one set before or the default one (SimpleReportFormatter). Reports are stored either to directory set before via setReportDirectory method or to the default one (./reports).
 * @param report - instance of Report received upon successful analysis
 * @param fileName - name of the file to store results to
 * @return true if the Report was formatted and saved, false otherwise
 */
public static boolean formatReport(Report report,String fileName){
  ReportFormatter formatter;
  try {
    formatter=INSTANCE.createFormatter();
  }
 catch (  InstantiationException ex) {
    return false;
  }
  File output=createFile(INSTANCE.getReportDir(),fileName,formatter.getReportFileExtension());
  Writer writer;
  try {
    writer=new FileWriter(output);
  }
 catch (  IOException ex) {
    logger.error("Unable to create FileWriter",ex);
    return false;
  }
  formatter.formatAndStore(report,writer);
  try {
    writer.close();
  }
 catch (  IOException ex) {
    logger.error("Unable to close FileWriter",ex);
    return false;
  }
  return true;
}
 

Example 57

From project android_build, under directory /tools/droiddoc/src/.

Source file: Proofread.java

  16 
vote

public static void initProofread(String filename){
  try {
    out=new FileWriter(filename);
    out.write("javadoc proofread file: " + filename + "\n");
  }
 catch (  IOException e) {
    if (out != null) {
      try {
        out.close();
      }
 catch (      IOException ex) {
      }
      out=null;
    }
    System.err.println("error opening file: " + filename);
  }
}
 

Example 58

From project Bitcoin-Wallet-for-Android, under directory /wallet/src/de/schildbach/wallet/ui/.

Source file: WalletActivity.java

  16 
vote

private void exportPrivateKeys(final String password){
  try {
    Constants.EXTERNAL_WALLET_BACKUP_DIR.mkdirs();
    final File file=new File(Constants.EXTERNAL_WALLET_BACKUP_DIR,Constants.EXTERNAL_WALLET_KEY_BACKUP + "-" + Iso8601Format.newDateFormat().format(new Date()));
    final Wallet wallet=getWalletApplication().getWallet();
    final ArrayList<ECKey> keys=wallet.keychain;
    final StringWriter plainOut=new StringWriter();
    WalletUtils.writeKeys(plainOut,keys);
    plainOut.close();
    final String plainText=plainOut.toString();
    final String cipherText=EncryptionUtils.encrypt(plainText,password.toCharArray());
    final Writer cipherOut=new FileWriter(file);
    cipherOut.write(cipherText);
    cipherOut.close();
    new AlertDialog.Builder(this).setInverseBackgroundForced(true).setMessage(getString(R.string.wallet_export_keys_dialog_success,file)).setNeutralButton(R.string.button_dismiss,null).show();
  }
 catch (  final IOException x) {
    new AlertDialog.Builder(this).setInverseBackgroundForced(true).setIcon(android.R.drawable.ic_dialog_alert).setTitle(R.string.wallet_import_export_keys_dialog_failure_title).setMessage(getString(R.string.wallet_export_keys_dialog_failure,x.getMessage())).setNeutralButton(R.string.button_dismiss,null).show();
    x.printStackTrace();
  }
}
 

Example 59

From project cargo-maven2-plugin-db, under directory /src/main/java/org/codehaus/cargo/maven2/.

Source file: DependencyCalculator.java

  16 
vote

void fixupProjectArtifact() throws FileNotFoundException, IOException, XmlPullParserException, ArtifactResolutionException, ArtifactNotFoundException, InvalidDependencyVersionException, ProjectBuildingException, ArtifactInstallationException {
  MavenProject mp2=new MavenProject(mavenProject);
  for (Iterator i=mp2.createArtifacts(artifactFactory,null,null).iterator(); i.hasNext(); ) {
    Artifact art=(Artifact)i.next();
    if (art.getType().equals("war")) {
      Artifact art2=artifactFactory.createArtifactWithClassifier(art.getGroupId(),art.getArtifactId(),art.getVersion(),"pom",null);
      fixupRepositoryArtifact(art2);
    }
  }
  Model pomFile=mp2.getModel();
  File outFile=File.createTempFile("pom",".xml");
  MavenXpp3Writer pomWriter=new MavenXpp3Writer();
  pomWriter.write(new FileWriter(outFile),pomFile);
  MavenXpp3Reader pomReader=new MavenXpp3Reader();
  pomFile=pomReader.read(new FileReader(outFile));
  Artifact art=mp2.getArtifact();
  fixModelAndSaveInRepository(art,pomFile);
  outFile.delete();
}
 

Example 60

From project cdk, under directory /generator/src/main/java/org/richfaces/cdk/.

Source file: OutputFileManagerImpl.java

  16 
vote

@Override public Writer createOutput(String path,long lastModified) throws IOException {
  if (null == path) {
    throw new NullPointerException("Output file path is null");
  }
  if (null == folder) {
    throw new FileNotFoundException("No output folder set for file " + path);
  }
  if (folder.exists() && !folder.isDirectory()) {
    throw new IOException("Output folder " + folder + " not is directory.");
  }
  if (path.startsWith(File.separator)) {
    path=path.substring(1);
  }
  File outputFile=new File(folder,path);
  if (outputFile.exists()) {
    if (lastModified > 0 && outputFile.lastModified() > lastModified) {
      return null;
    }
 else {
      outputFile.delete();
    }
  }
  outputFile.getParentFile().mkdirs();
  outputFile.createNewFile();
  return new FileWriter(outputFile);
}
 

Example 61

From project clirr-maven-plugin, under directory /src/main/java/org/codehaus/mojo/clirr/.

Source file: ClirrReport.java

  16 
vote

protected void doExecute() throws MojoExecutionException, MojoFailureException {
  if (!canGenerateReport()) {
    return;
  }
  try {
    DecorationModel model=new DecorationModel();
    model.setBody(new Body());
    Map attributes=new HashMap();
    attributes.put("outputEncoding","UTF-8");
    Locale locale=Locale.getDefault();
    SiteRenderingContext siteContext=siteRenderer.createContextForSkin(getSkinArtifactFile(),attributes,model,getName(locale),locale);
    RenderingContext context=new RenderingContext(outputDirectory,getOutputName() + ".html");
    SiteRendererSink sink=new SiteRendererSink(context);
    generate(sink,locale);
    outputDirectory.mkdirs();
    Writer writer=new FileWriter(new File(outputDirectory,getOutputName() + ".html"));
    siteRenderer.generateDocument(writer,sink,siteContext);
    siteRenderer.copyResources(siteContext,new File(project.getBasedir(),"src/site/resources"),outputDirectory);
  }
 catch (  RendererException e) {
    throw new MojoExecutionException("An error has occurred in " + getName(Locale.ENGLISH) + " report generation.",e);
  }
catch (  IOException e) {
    throw new MojoExecutionException("An error has occurred in " + getName(Locale.ENGLISH) + " report generation.",e);
  }
catch (  MavenReportException e) {
    throw new MojoExecutionException("An error has occurred in " + getName(Locale.ENGLISH) + " report generation.",e);
  }
}
 

Example 62

From project 16Blocks, under directory /src/main/java/de/minestar/sixteenblocks/Commands/.

Source file: cmdSlots.java

  15 
vote

private void setSlots(String[] args,CommandSender sender){
  try {
    Integer maxPlayer=Integer.valueOf(args[0]);
    CraftServer server=(CraftServer)Bukkit.getServer();
    server.getHandle().maxPlayers=maxPlayer;
    ChatUtils.writeSuccess(sender,"MaxPlayers set to " + maxPlayer + " !");
    Properties p=new Properties();
    BufferedReader bReader=new BufferedReader(new FileReader("server.properties"));
    p.load(bReader);
    bReader.close();
    p.setProperty("max-players",maxPlayer.toString());
    BufferedWriter bWriter=new BufferedWriter(new FileWriter("server.properties"));
    p.store(bWriter,"");
    bWriter.close();
  }
 catch (  IOException IOE) {
    ConsoleUtils.printException(IOE,"Can't update server.properties!");
  }
catch (  NumberFormatException e) {
    ChatUtils.writeError(sender,args[0] + " is not a number!");
  }
}
 

Example 63

From project Aardvark, under directory /aardvark-interactive/src/test/java/gw/vark/.

Source file: InteractiveShellTest.java

  15 
vote

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 64

From project AceWiki, under directory /src/ch/uzh/ifi/attempto/aceeditor/test/.

Source file: ChartParserGenerationTest.java

  15 
vote

/** 
 * Starts the test.
 * @param args
 */
public static void main(String[] args){
  try {
    out=new BufferedWriter(new FileWriter("src/ch/uzh/ifi/attempto/aceeditor/test/sentences_cp.txt"));
  }
 catch (  IOException ex) {
    ex.printStackTrace();
  }
  System.err.print("\n0");
  long timestart=System.currentTimeMillis();
  completeSentence();
  long timeend=System.currentTimeMillis();
  System.err.print("\n\nTime needed in seconds: " + (timeend - timestart) / 1000.0 + "\n");
  try {
    out.close();
  }
 catch (  IOException ex) {
    ex.printStackTrace();
  }
}
 

Example 65

From project AdminCmd, under directory /src/main/java/be/Balor/Tools/.

Source file: Downloader.java

  15 
vote

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 66

From project agileBase, under directory /gtpb_server/src/com/gtwm/pb/util/.

Source file: Helpers.java

  15 
vote

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 67

From project alg-vis, under directory /src/algvis/scenario/.

Source file: Scenario.java

  15 
vote

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 68

From project android-context, under directory /src/edu/fsu/cs/contextprovider/.

Source file: ContextExpandableListActivity.java

  15 
vote

public void exportToFile() throws IOException {
  String path=Environment.getExternalStorageDirectory() + "/" + CSV_FILENAME;
  File file=new File(path);
  file.createNewFile();
  if (!file.isFile()) {
    throw new IllegalArgumentException("Should not be a directory: " + file);
  }
  if (!file.canWrite()) {
    throw new IllegalArgumentException("File cannot be written: " + file);
  }
  Writer output=new BufferedWriter(new FileWriter(file));
  HashMap<String,String> cntx=null;
  String line;
  cntx=ContextProvider.getAllUnordered();
  for (  LinkedHashMap.Entry<String,String> entry : cntx.entrySet()) {
    ContextListItem item=new ContextListItem();
    item.setName(entry.getKey());
    item.setValue(entry.getValue());
    line=item.toString();
    output.write(line + "\n");
  }
  output.close();
  Toast.makeText(this,String.format("Saved",path),Toast.LENGTH_LONG).show();
  Intent shareIntent=new Intent(Intent.ACTION_SEND);
  shareIntent.putExtra(Intent.EXTRA_STREAM,Uri.parse("file://" + path));
  shareIntent.setType("text/plain");
  startActivity(Intent.createChooser(shareIntent,"Share Context Using..."));
}
 

Example 69

From project android_packages_apps_VoiceDialer_2, under directory /src/com/android/voicedialer/.

Source file: RecognizerLogger.java

  15 
vote

/** 
 * 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 70

From project Anki-Android, under directory /src/com/ichi2/anki/.

Source file: Utils.java

  15 
vote

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 71

From project ant4eclipse, under directory /org.ant4eclipse.lib.jdt/src/org/ant4eclipse/lib/jdt/internal/model/jre/support/.

Source file: LibraryDetector.java

  15 
vote

/** 
 * 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 72

From project arquillian-extension-persistence, under directory /impl/src/main/java/org/jboss/arquillian/persistence/core/client/.

Source file: DatabaseStateDumper.java

  15 
vote

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 73

From project arquillian-rusheye, under directory /rusheye-impl/src/main/java/org/jboss/rusheye/oneoff/.

Source file: XmlWriter.java

  15 
vote

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 74

From project artimate, under directory /artimate-demo/src/main/java/com/jdotsoft/jarloader/.

Source file: JarClassLoader.java

  15 
vote

/** 
 * 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 75

From project asadmin, under directory /asadmin-java/src/main/java/org/n0pe/asadmin/commands/.

Source file: CreateFileUser.java

  15 
vote

@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 76

From project authme-2.0, under directory /src/uk/org/whoami/authme/datasource/.

Source file: FileDataSource.java

  15 
vote

@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 77

From project AuthMe-Reloaded-Charge-fix, under directory /src/uk/org/whoami/authme/datasource/.

Source file: FileDataSource.java

  15 
vote

@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 78

From project babel, under directory /src/babel/util/dict/.

Source file: SimpleDictionary.java

  15 
vote

public void write(String fileName) throws Exception {
  BufferedWriter writer=new BufferedWriter(new FileWriter(fileName));
  for (  String key : m_map.keySet()) {
    for (    String val : m_map.get(key)) {
      writer.write(key + "\t" + val);
      writer.newLine();
    }
  }
  writer.close();
}
 

Example 79

From project behemoth, under directory /gate/src/main/java/com/digitalpebble/behemoth/gate/.

Source file: GATECorpusGenerator.java

  15 
vote

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 80

From project BG7, under directory /src/com/era7/bioinfo/annotation/.

Source file: FixFastaHeaders.java

  15 
vote

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 81

From project Bio-PEPA, under directory /uk.ac.ed.inf.biopepa.ui/lib/opencsv-2.1/test/au/com/bytecode/opencsv/.

Source file: OpencsvTest.java

  15 
vote

/** 
 * Test the full cycle of write-read
 */
@Test public void testWriteRead() throws IOException {
  final String[][] data=new String[][]{{"hello, a test","one nested \" test"},{"\"\"","test",null,"8"}};
  writer=new CSVWriter(new FileWriter(tempFile));
  for (int i=0; i < data.length; i++) {
    writer.writeNext(data[i]);
  }
  writer.close();
  reader=new CSVReader(new FileReader(tempFile));
  String[] line;
  for (int row=0; (line=reader.readNext()) != null; row++) {
    assertTrue(line.length == data[row].length);
    for (int col=0; col < line.length; col++) {
      if (data[row][col] == null) {
        assertTrue(line[col].equals(""));
      }
 else {
        assertTrue(line[col].equals(data[row][col]));
      }
    }
  }
  reader.close();
}
 

Example 82

From project Bio4j, under directory /src/main/java/com/era7/bioinfo/bio4j/codesamples/.

Source file: GetGOAnnotationsForOrganism.java

  15 
vote

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 83

From project bioclipse.seneca, under directory /plugins/net.bioclipse.seneca/src/org/openscience/cdk/structgen/deterministic/.

Source file: GENMDeterministicGenerator.java

  15 
vote

/** 
 * Constructor for the GENMDeterministicGenerator. Allows for setting the molecular formula for which the isomers are to be generated as well as for setting an output path for a file with generated structures.
 * @param mf	 molecular formula string
 * @param path Path to the file used for writing structures. Leave blank if current directory should be used.If set to null then no structure file is written.
 */
public GENMDeterministicGenerator(String mf,String path) throws Exception {
  logger=LoggingToolFactory.createLoggingTool(GENMDeterministicGenerator.class);
  builder=NoNotificationChemObjectBuilder.getInstance();
  numberOfSetFragment=0;
  numberOfStructures=0;
  logger.debug(mf);
  IMolecularFormula formula=MolecularFormulaManipulator.getMolecularFormula(mf,this.builder);
  molecularFormula=new int[12];
  numberOfBasicUnit=new int[23];
  numberOfBasicFragment=new int[34];
  basicFragment=new ArrayList();
  structures=new ArrayList();
  listeners=new ArrayList();
  if (path != null)   structureout=new PrintWriter(new FileWriter(path + "structuredata.txt"),true);
 else   structureout=null;
  initializeParameters();
  analyseMolecularFormula(formula);
}
 

Example 84

From project BioMAV, under directory /Behavior/src/nl/ru/ai/projects/parrot/tools/.

Source file: Writer.java

  15 
vote

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 85

From project Bit4Tat, under directory /Bit4Tat/src/com/Bit4Tat/.

Source file: WalletFileIO.java

  15 
vote

/** 
 * 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 86

From project BlameSubversion-plugin, under directory /src/main/java/hudson/scm/.

Source file: BlameSubversionSCM.java

  15 
vote

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 87

From project BMach, under directory /src/bmach/ui/gui/.

Source file: BMachPanel.java

  15 
vote

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 88

From project bonecp, under directory /bonecp-benchmark/src/main/java/com/jolbox/benchmark/.

Source file: BenchmarkLaunch.java

  15 
vote

/** 
 * @param title 
 * @param filename 
 * @param results 
 * @throws IOException 
 */
private static void plotBarGraph(String title,String filename,long[] results) throws IOException {
  String fname=System.getProperty("java.io.tmpdir") + File.separator + filename;
  PrintWriter out=new PrintWriter(new FileWriter(fname + ".txt"));
  DefaultCategoryDataset dataset=new DefaultCategoryDataset();
  for (  ConnectionPoolType poolType : ConnectionPoolType.values()) {
    dataset.setValue(results[poolType.ordinal()],"ms",poolType);
    out.println(results[poolType.ordinal()] + "," + poolType);
  }
  out.close();
  JFreeChart chart=ChartFactory.createBarChart(title,"Connection Pool","Time (ms)",dataset,PlotOrientation.VERTICAL,false,true,false);
  try {
    ChartUtilities.saveChartAsPNG(new File(fname),chart,1024,768);
    System.out.println("******* Saved chart to: " + fname);
  }
 catch (  IOException e) {
    e.printStackTrace();
    System.err.println("Problem occurred creating chart.");
  }
}
 

Example 89

From project book, under directory /src/main/java/com/tamingtext/tagging/.

Source file: LuceneTagExtractor.java

  15 
vote

public static void emitTextForTags(File file,File output) throws IOException {
  String field="tag";
  Directory dir=FSDirectory.open(file);
  IndexReader reader=IndexReader.open(dir,true);
  TermEnum te=reader.terms(new Term(field,""));
  StringBuilder buf=new StringBuilder();
  do {
    Term term=te.term();
    if (term == null || term.field().equals(field) == false) {
      break;
    }
    if (te.docFreq() > 30) {
      File f=new File(output,term.text() + ".txt");
      PrintWriter pw=new PrintWriter(new FileWriter(f));
      System.err.printf("%s %d\n",term.text(),te.docFreq());
      TermDocs td=reader.termDocs(term);
      while (td.next()) {
        int doc=td.doc();
        buf.setLength(0);
        appendVectorTerms(buf,reader.getTermFreqVector(doc,"description-clustering"));
        appendVectorTerms(buf,reader.getTermFreqVector(doc,"extended-clustering"));
        emitTagDoc(term,pw,buf);
      }
      pw.close();
    }
  }
 while (te.next());
  te.close();
}
 

Example 90

From project build-info, under directory /build-info-api/src/test/java/org/jfrog/build/api/.

Source file: FileChecksumCalculatorTest.java

  15 
vote

/** 
 * 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 91

From project Catroid-maven-playground, under directory /src/main/java/at/tugraz/ist/catroid/io/.

Source file: StorageHandler.java

  15 
vote

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 92

From project cider, under directory /src/net/yacy/cider/util/.

Source file: FileUtils.java

  15 
vote

/** 
 * 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 93

From project cilia-workbench, under directory /cilia-workbench-designer/src/fr/liglab/adele/cilia/workbench/designer/service/common/.

Source file: AbstractRepoService.java

  15 
vote

/** 
 * 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 94

From project CircDesigNA, under directory /src/circdesigna/plugins/.

Source file: RunNupackTool.java

  15 
vote

public static void runNupack(String seqs,String concs,int maximumComplexSize,String prefix,int opcode,File nupackDir) throws IOException {
  System.err.println(nupackDir.getAbsolutePath() + "/" + prefix);
  nupackDir.mkdirs();
  File nupackList=new File("nupackTest/" + prefix + ".in");
  PrintWriter nuPackListOut=new PrintWriter(new FileWriter(nupackList));
  nuPackListOut.print(seqs);
  nuPackListOut.println(maximumComplexSize);
  nuPackListOut.close();
  PrintWriter conOut=new PrintWriter(new FileWriter(new File("nupackTest/" + prefix + ".con")));
  conOut.print(concs);
  conOut.close();
  if (opcode == OPCODE_MFE) {
    runProcess(System.getProperty("NUPACKHOME") + "/bin/mfe -multi -material dna " + prefix,new String[]{"NUPACKHOME=" + System.getProperty("NUPACKHOME")},nupackDir);
  }
  if (opcode == OPCODE_COMPLEXES_AND_CONC || opcode == OPCODE_COMPLEXES) {
    runProcess(System.getProperty("NUPACKHOME") + "/bin/complexes -material dna -pairs " + prefix,new String[]{"NUPACKHOME=" + System.getProperty("NUPACKHOME")},nupackDir);
  }
  if (opcode == OPCODE_COMPLEXES_AND_CONC) {
    runProcess(System.getProperty("NUPACKHOME") + "/bin/concentrations -sort 0 " + prefix,new String[]{"NUPACKHOME=" + System.getProperty("NUPACKHOME")},nupackDir);
  }
}
 

Example 95

From project Clotho-Core, under directory /ClothoApps/SeqAnalyzer/src/org/clothocad/algorithm/seqanalyzer/sequencing/.

Source file: seqAnalysis.java

  15 
vote

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 96

From project clutter, under directory /src/com/thoughtworks/ashcroft/runtime/.

Source file: JohnAshcroft.java

  15 
vote

private static void initializeLogWriter(){
  if (LOGGING.equals("stdout")) {
    LOG_WRITER=new PrintWriter(System.out);
  }
 else   if (LOGGING.equals("stderr")) {
    LOG_WRITER=new PrintWriter(System.err);
  }
 else {
    try {
      LOG_WRITER=new PrintWriter(new FileWriter(LOGGING));
    }
 catch (    IOException e) {
      System.err.println("Ashcroft couldn't write log to " + LOGGING);
      e.printStackTrace(System.err);
      System.exit(-1);
    }
  }
}
 

Example 97

From project codjo-imports, under directory /codjo-imports-release-test/src/test/java/net/codjo/imports/release_test/common/.

Source file: GlobalImportTest.java

  15 
vote

private File createFile(String[] content) throws IOException {
  File file=new File(directoryFixture,"testImport.txt");
  PrintWriter in=new PrintWriter(new FileWriter(file));
  try {
    for (    String aContent : content) {
      in.println(aContent);
    }
  }
  finally {
    in.close();
  }
  return file;
}
 

Example 98

From project codjo-webservices, under directory /codjo-webservices-generator/src/main/java/net/codjo/webservices/generator/.

Source file: ClassListGenerator.java

  15 
vote

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 99

From project cogroo4, under directory /cogroo-nlp/src/main/java/opennlp/tools/formats/ad/.

Source file: SentenceTest.java

  15 
vote

public static void main(String[] a) throws Exception {
  ADTokenSampleStreamFactory factory=new ADTokenSampleStreamFactory(ADTokenSampleStreamFactory.Parameters.class);
  File dict=new File("/Users/wcolen/Documents/wrks/opennlp/opennlp/opennlp-tools/lang/pt/tokenizer/pt-detokenizer.xml");
  File data=new File("/Users/wcolen/Documents/wrks/corpus/Bosque/Bosque_CF_8.0.ad.txt");
  String[] args={"-data",data.getCanonicalPath(),"-encoding","ISO-8859-1","-lang","pt","-detokenizer",dict.getCanonicalPath()};
  ObjectStream<TokenSample> tokenSampleStream=factory.create(args);
  TokenSample sample=tokenSampleStream.read();
  BufferedWriter fromNameSample=new BufferedWriter(new FileWriter("fromNameSample.txt"));
  while (sample != null) {
    fromNameSample.append(sample.getText().toLowerCase() + "\n");
    sample=tokenSampleStream.read();
  }
  fromNameSample.close();
  FileInputStream sampleDataIn=new FileInputStream(data);
  ObjectStream<SentenceSample> sampleStream=new ADSentenceSampleStream(new PlainTextByLineStream(sampleDataIn.getChannel(),"ISO-8859-1"),true);
  SentenceSample sentSample=sampleStream.read();
  BufferedWriter fromSentence=new BufferedWriter(new FileWriter("fromSentence.txt"));
  while (sentSample != null) {
    String[] sentences=Span.spansToStrings(sentSample.getSentences(),sentSample.getDocument());
    for (    String string : sentences) {
      fromSentence.append(string.toLowerCase() + "\n");
    }
    sentSample=sampleStream.read();
  }
  fromSentence.close();
}
 

Example 100

From project collaborative-editor, under directory /mpedit/gui/.

Source file: CFileActions.java

  15 
vote

/** 
 * @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;
}