Java Code Examples for java.io.BufferedWriter

The following are top voted examples for showing how to use java.io.BufferedWriter. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: MinecraftSecondScreenMod   File: DataStorageDriver.java View source code Vote up 7 votes
private static void writeToFile(File file, ArrayList<String> lines) {
	try {
		getSaveDir().mkdirs();
		file.createNewFile();
		file.setReadable(true);
		file.setWritable(true);
		BufferedWriter writer = new BufferedWriter(new FileWriter(file));
		for (String line : lines) {
			writer.append(line);
			writer.newLine();
		}
		writer.flush();
		writer.close();

	} catch (IOException e) {
		e.printStackTrace();
		Logger.e(TAG, "Failed writing the String Array to the file: " + file.getAbsolutePath(), e);
	}
}
 
Example 2
Project: aws-toolkit-eclipse   File: NewAccessKeyDialog.java View source code Vote up 6 votes
private void saveFile(String fileName) throws IOException {
    File f = new File(fileName);
    // Check whether the file already exists.
    if (f.createNewFile() == false) {
        throw new IOException("File already exists " + fileName);
    }
    String content = "";
    FileWriter fstream = new FileWriter(f.getAbsoluteFile());
    BufferedWriter out = new BufferedWriter(fstream);
    out.write("\"User Name\",\"Access Key Id\",\"Secret Access Key\"\n");
    content += "\"" + userName + "\",";
    content += "\"" + createAccessKeyResult.getAccessKey().getAccessKeyId() + "\",";
    content += "\"" + createAccessKeyResult.getAccessKey().getSecretAccessKey() + "\"";
    out.write(content);
    out.close();
}
 
Example 3
Project: ArubaSyslog   File: UserSessions.java View source code Vote up 6 votes
/**
   * Split the whole wifilogs into individual users.
   * @param input
   * @param output
   * @throws IOException
* @throws ParseException 
   */
  private static void splitAndExtract(String input, String output) throws IOException, ParseException{
      
  	File[] files = Utils.getInputFiles(input);
      Utils.createFolder(output);
      Arrays.sort(files);
      
      for ( File file : files){
      	Map<String, List<String>> macRecordMap = new HashMap<String, List<String>>();
      	long start  = System.currentTimeMillis();
      	System.out.println(start/1000 + " " + file.getName());
      	String line = null;
      	BufferedReader iReader  = new BufferedReader(new FileReader(file));
      	
      	System.out.println("Split syslogs into users...");
      	while ((line = iReader.readLine()) != null) {
      		String[] parts = line.split("\t", 2);
      		if (parts.length == 2){
      			String mac = parts[0];
      			if ( !macRecordMap.containsKey(mac) ){
      				macRecordMap.put(mac, new ArrayList<String>());
      			}
      			macRecordMap.get(mac).add(line);
      		}
      	}
      	iReader.close();
      	
      	System.out.println("Extract sessions...");
      	for ( String umac : macRecordMap.keySet()){
      		if ( Utils.debug )
      			System.out.println(umac);
      		
      		// extract session and save to file
              List<String> finalLines = SessionExtraction.extractSessions(macRecordMap.get(umac));
              
              // write into file
              BufferedWriter bw = new BufferedWriter(new FileWriter(FilenameUtils.concat(output, FilenameUtils.getName(file.getName())), true));
              for ( String l : finalLines )
                  bw.write(l + "\n");
              bw.close();
      	}
      	
      	macRecordMap.clear();
      	System.out.println(String.format("Elapsed time: %.3f sec",
                  (System.currentTimeMillis() - start)/1000.0));
      }
  }
 
Example 4
Project: dlna   File: FileHelper.java View source code Vote up 6 votes
public static boolean writeFile(String filePath, String fileContent, boolean append) {
	if (null == filePath || fileContent == null || filePath.length() < 1 || fileContent.length() < 1) {
		log.e("Invalid param. filePath: " + filePath + ", fileContent: " + fileContent);
		return false;
	}
	
	try {
       File file = new File(filePath);
       if (!file.exists()) {
    	   if (!file.createNewFile()) {
    		   return false;
    	   }
       }
       
       BufferedWriter output = new BufferedWriter(new FileWriter(file, append));
       output.write(fileContent);
       output.flush();
       output.close();
	} catch (IOException ioe) {
		log.e("writeFile ioe: " + ioe.toString());
		return false;
	}
	
	return true;
}
 
Example 5
Project: strongback-java   File: NewProject.java View source code Vote up 6 votes
protected static void copyTo(File input, File output, Function<String, String> each) throws IOException {
    BufferedReader testReader = new BufferedReader(new FileReader(input));
    BufferedWriter testWriter = new BufferedWriter(new FileWriter(output));
    try {
        while(testReader.ready()) {
            testWriter.write(each.apply(testReader.readLine().replace("DATE", new Date().toString())));
            testWriter.newLine();
        }
    } finally {
        testWriter.close();
        testReader.close();
    }
}
 
Example 6
Project: JAME   File: DefaultConfigConverter.java View source code Vote up 6 votes
private void save(final Writer w) throws IOException {
	BufferedWriter writer = new BufferedWriter(w);
	writer.write("#don't remove this line!\n");
	writer.write("jame fractal 3.1:" + getType());
	writer.write(":" + formulamodule);
	writer.write(":" + insidemethodmodule);
	writer.write(":" + outsidemethodmodule);
	double[] parameters = getParameters();
	for (int i = 0; i < 6; i++) {
		writer.write(":" + Double.toString(parameters[i]));
	}
	writer.write(":" + iterations + "\n");
	writer.write(formulaoptions + "\n");
	writer.write(insidemethodoptions + "\n");
	writer.write(outsidemethodoptions + "\n");
	writer.write(insidepalette + "\n");
	writer.write(outsidepalette + "\n");
	writer.close();
}
 
Example 7
Project: speechalyzer   File: Util.java View source code Vote up 6 votes
/**
 * Write some String to a file.
 * 
 * @param content
 *            The String.
 * @param fileName
 *            Description of the Parameter
 * @exception Exception
 *                Description of the Exception
 */
public static void writeFileContent(String fileName, String content)
		throws Exception {
	BufferedWriter bw = null;
	try {
		bw = new BufferedWriter(new FileWriter(fileName));
		bw.write(content);
	} catch (Exception e) {
		System.err.println("error trying to get file content"
				+ e.toString());
		// e.printStackTrace();
	} finally {
		bw.close();
		bw = null;
	}
}
 
Example 8
Project: jlibs   File: PropertiesUtil.java View source code Vote up 6 votes
public static void writeComments(BufferedWriter bw,  String comments) throws IOException{
    bw.write("#");
    int len = comments.length();
    int current = 0;
    int last = 0;
    char[] uu = new char[6];
    uu[0] = '\\';
    uu[1] = 'u';
    while(current<len){
        char c = comments.charAt(current);
     if(c>'\u00ff' || c=='\n' || c=='\r'){
         if(last != current)
                bw.write(comments.substring(last, current));
            if(c>'\u00ff'){
                uu[2] = toHex((c >> 12) & 0xf);
                uu[3] = toHex((c >>  8) & 0xf);
                uu[4] = toHex((c >>  4) & 0xf);
                uu[5] = toHex( c        & 0xf);
                bw.write(new String(uu));
            }else{
                bw.newLine();
                if(c=='\r' && current!=len-1 && comments.charAt(current+1)=='\n'){
                    current++;
                }
                if(current==len-1 || (comments.charAt(current + 1)!='#' && comments.charAt(current+1)!='!'))
                    bw.write("#");
            }
            last = current + 1;
     }
        current++;
 }
    if(last!=current)
        bw.write(comments.substring(last, current));
    bw.newLine();
}
 
Example 9
Project: webstart   File: VersionXmlGenerator.java View source code Vote up 6 votes
private void generateXml( BufferedWriter writer, Collection<ResolvedJarResource> jarResources )
    throws IOException
{

    writer.write( "<?xml version=\"1.0\"?>" );
    writer.newLine();
    writer.write( "<jnlp-versions>" );
    writer.newLine();

    for ( ResolvedJarResource jarResource : jarResources )
    {
        writer.write( "  <resource>" );
        writer.newLine();
        writer.write( "    <pattern>" );
        writer.newLine();
        writer.write( "      <name>" );
        writer.write( jarResource.getHrefValue() );
        writer.write( "</name>" );
        writer.newLine();
        writer.write( "      <version-id>" );
        writer.write( jarResource.getVersion() );
        writer.write( "</version-id>" );
        writer.newLine();
        writer.write( "    </pattern>" );
        writer.newLine();
        writer.write( "    <file>" );
        writer.write( jarResource.getArtifact().getFile().getName() );
        writer.write( "</file>" );
        writer.newLine();
        writer.write( "  </resource>" );
        writer.newLine();
    }

    writer.write( "</jnlp-versions>" );
    writer.newLine();
}
 
Example 10
Project: aipo   File: TimelineUrlScreen.java View source code Vote up 6 votes
/**
 * 
 * @param rundata
 * @param context
 * @throws Exception
 */
@Override
protected void doOutput(RunData rundata, Context context) throws Exception {

  try {
    String url = ALEipUtils.getParameter(rundata, context, "url");
    TimelineUrlBeans listdata = TimelineUtils.perseFromUrl(url);
    if (listdata != null) {
      setResultData(listdata);
      putData(rundata, context);
    } else {
      try {
        BufferedWriter writer;
        ServletOutputStream out = null;
        HttpServletResponse response = rundata.getResponse();
        out = response.getOutputStream();
        writer =
          new BufferedWriter(new OutputStreamWriter(
            out,
            ALEipConstants.DEF_CONTENT_ENCODING));
        writer.write("error");
        writer.flush();
        writer.close();
        return;
      } catch (Exception e) {
        logger.error("[ALVelocityScreen]", e);
      }
    }
    String layout_template = "portlets/html/ajax-timeline-url.vm";
    setTemplate(rundata, context, layout_template);

  } catch (Exception ex) {
    logger.error("[TimelineScreen] Exception.", ex);
    ALEipUtils.redirectDBError(rundata);
  }
}
 
Example 11
Project: easyccg   File: Rebanker.java View source code Vote up 6 votes
private void writeCatList(Multiset<Category> cats, File outputFile) throws IOException {
  Multiset<Category> catsNoPPorPRfeatures = HashMultiset.create();
  for (Category cat : cats) {
    catsNoPPorPRfeatures.add(cat.dropPPandPRfeatures());
  }
  FileWriter fw = new FileWriter(outputFile.getAbsoluteFile());
  BufferedWriter bw = new BufferedWriter(fw);
  
  
  int categories = 0;
  for (Category type : Multisets.copyHighestCountFirst(cats).elementSet()) {
    if (catsNoPPorPRfeatures.count(type.dropPPandPRfeatures()) >= 10) {
      bw.write(type.toString());
      bw.newLine();
      categories++;
    }
  }
  System.out.println("Number of cats occurring 10 times: " + categories);
  
  
  bw.flush();
  bw.close();
  

}
 
Example 12
Project: Solr-Javadoc   File: Analyzer.java View source code Vote up 6 votes
public static void main(String[] args) throws IOException {
        File outputFile = new File(args[0]);
        WRITER = new BufferedWriter(new FileWriter(outputFile), 10000);
        WRITER.write("digraph G {\n");

        Main.execute("JavadocIndexer", "com.solrstart.javadoc.dependencies.Analyzer", new String[]{
                "-sourcepath",
                "/Volumes/RAMDisk/source-solr-4.7.0/lucene/analysis/common/src/java:/Volumes/RAMDisk/source-solr-4.7.0/lucene/analysis/icu/src/java:/Volumes/RAMDisk/source-solr-4.7.0/lucene/analysis/kuromoji/src/java:/Volumes/RAMDisk/source-solr-4.7.0/lucene/analysis/morfologik/src/java:/Volumes/RAMDisk/source-solr-4.7.0/lucene/analysis/phonetic/src/java:/Volumes/RAMDisk/source-solr-4.7.0/lucene/analysis/smartcn/src/java:/Volumes/RAMDisk/source-solr-4.7.0/lucene/analysis/stempel/src/java:/Volumes/RAMDisk/source-solr-4.7.0/lucene/analysis/uima/src/java:/Volumes/RAMDisk/source-solr-4.7.0/lucene/codecs/src/java:/Volumes/RAMDisk/source-solr-4.7.0/lucene/core/src/java:/Volumes/RAMDisk/source-solr-4.7.0/lucene/expressions/src/java:/Volumes/RAMDisk/source-solr-4.7.0/lucene/grouping/src/java:/Volumes/RAMDisk/source-solr-4.7.0/lucene/highlighter/src/java:/Volumes/RAMDisk/source-solr-4.7.0/lucene/join/src/java:/Volumes/RAMDisk/source-solr-4.7.0/lucene/memory/src/java:/Volumes/RAMDisk/source-solr-4.7.0/lucene/misc/src/java:/Volumes/RAMDisk/source-solr-4.7.0/lucene/queries/src/java:/Volumes/RAMDisk/source-solr-4.7.0/lucene/queryparser/src/java:/Volumes/RAMDisk/source-solr-4.7.0/lucene/spatial/src/java:/Volumes/RAMDisk/source-solr-4.7.0/lucene/suggest/src/java:/Volumes/RAMDisk/source-solr-4.7.0/solr/contrib/analysis-extras/src/java:/Volumes/RAMDisk/source-solr-4.7.0/solr/contrib/clustering/src/java:/Volumes/RAMDisk/source-solr-4.7.0/solr/contrib/dataimporthandler-extras/src/java:/Volumes/RAMDisk/source-solr-4.7.0/solr/contrib/dataimporthandler/src/java:/Volumes/RAMDisk/source-solr-4.7.0/solr/contrib/extraction/src/java:/Volumes/RAMDisk/source-solr-4.7.0/solr/contrib/langid/src/java:/Volumes/RAMDisk/source-solr-4.7.0/solr/contrib/map-reduce/src/java:/Volumes/RAMDisk/source-solr-4.7.0/solr/contrib/morphlines-cell/src/java:/Volumes/RAMDisk/source-solr-4.7.0/solr/contrib/morphlines-core/src/java:/Volumes/RAMDisk/source-solr-4.7.0/solr/contrib/uima/src/java:/Volumes/RAMDisk/source-solr-4.7.0/solr/contrib/velocity/src/java:/Volumes/RAMDisk/source-solr-4.7.0/solr/core/src/java:/Volumes/RAMDisk/source-solr-4.7.0/solr/solrj/src/java",
//                "/Volumes/RAMDisk/source-solr-4.7.0/solr/core/src/java:/Volumes/RAMDisk/source-solr-4.7.0/lucene/core/src/java",
//                "/Volumes/RAMDisk/source-solr-4.7.0/solr/core/src/java",
                "-subpackages",
                "org.apache"
//        org.tartarus.snowball:org.apache.lucene:org.apache.solr:org.egothor.stemmer
        });

        WRITER.write("}\n");
        WRITER.close();

        //Then run graphviz:
        // dot -Tsvg -O -Grankdir=LR dependencies.dot
    }
 
Example 13
Project: jeql   File: IOFunction.java View source code Vote up 6 votes
public static boolean writeTextFile(String filename, String value)
{
  try {
    FileWriter fileWriter = new FileWriter(filename);
    BufferedWriter bufWriter = new BufferedWriter(fileWriter);
    bufWriter.write(value);
    bufWriter.close();
  }
  catch (IOException ex) {
    System.out.println(ex.getMessage());
    return false;
  }
  return true;
}
 
Example 14
Project: ilarkesto   File: IO.java View source code Vote up 6 votes
public static void writeFile(String file, Collection<String> lines) throws IOException {
	File f = new File(file);
	createDirectory(f.getParentFile());
	BufferedWriter out = new BufferedWriter(new FileWriter(f));
	for (String s : lines) {
		out.write(s);
		out.write("\n");
	}
	out.close();
}
 
Example 15
Project: proxima   File: NativeTools.java View source code Vote up 6 votes
private static String prepareRootCommandScript(Context context,
        String command)
{
    try
    {
        Log.d(TAG, "Root command ==> " + command);

        // create a dummy script so that the user doesn't have to constantly
        // accept the SuperUser prompt
        File scriptFile = new File(context.getFilesDir().getParent()
                + "/tmp/command.sh");
        scriptFile.delete(); // clear out old content

        scriptFile = new File(scriptFile.getAbsolutePath());
        scriptFile.getParentFile().mkdirs();
        scriptFile.createNewFile();

        BufferedWriter writer = new BufferedWriter(new FileWriter(
                scriptFile));
        // TODO: will this always be here?
        writer.append("#!/system/bin/sh\n");
        writer.append(command);
        writer.close();

        // set executable permissions
        runCommand("chmod 0755 " + scriptFile.getAbsolutePath());

        return "su -c \"" + scriptFile.getAbsolutePath() + "\"";

    }
    catch (Exception e)
    {
        e.printStackTrace();
        return null;
    }
}
 
Example 16
Project: jlibs   File: FileLogHandler.java View source code Vote up 6 votes
private void rotateIfNecessary(){
    try{
        long now = System.currentTimeMillis();
        if(now>=next){
            if(writer !=null)
                writer.close();
            File file = new File(dir, prefix+new SimpleDateFormat(format).format(new Date(now))+suffix);
            writer = new BufferedWriter(new FileWriter(file));
            next = repeatingDuration.next();
        }
    }catch(Throwable ex){
        ex.printStackTrace();
    }
}
 
Example 17
Project: phonegap-geolocation   File: DiskLruCache.java View source code Vote up 6 votes
/**
 * Creates a new journal that omits redundant information. This replaces the
 * current journal if it exists.
 */
private synchronized void rebuildJournal() throws IOException {
  if (journalWriter != null) {
    journalWriter.close();
  }

  Writer writer = new BufferedWriter(
      new OutputStreamWriter(new FileOutputStream(journalFileTmp), Util.US_ASCII));
  try {
    writer.write(MAGIC);
    writer.write("\n");
    writer.write(VERSION_1);
    writer.write("\n");
    writer.write(Integer.toString(appVersion));
    writer.write("\n");
    writer.write(Integer.toString(valueCount));
    writer.write("\n");
    writer.write("\n");

    for (Entry entry : lruEntries.values()) {
      if (entry.currentEditor != null) {
        writer.write(DIRTY + ' ' + entry.key + '\n');
      } else {
        writer.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n');
      }
    }
  } finally {
    writer.close();
  }

  if (journalFile.exists()) {
    renameTo(journalFile, journalFileBackup, true);
  }
  renameTo(journalFileTmp, journalFile, false);
  journalFileBackup.delete();

  journalWriter = new BufferedWriter(
      new OutputStreamWriter(new FileOutputStream(journalFile, true), Util.US_ASCII));
}
 
Example 18
Project: breakout   File: BuilderGenerator.java View source code Vote up 6 votes
private static void write( List<String> lines , File dest ) throws Exception
{
	BufferedWriter writer = new BufferedWriter( new FileWriter( dest ) );
	write( lines , writer );
	writer.flush( );
	writer.close( );
}
 
Example 19
Project: nmonvisualizer   File: CSVFileChooser.java View source code Vote up 6 votes
public void saveToCSV() {
    if (showDialog(gui.getMainFrame(), "Save") == JFileChooser.APPROVE_OPTION) {
        File csvFile = getSelectedFile();

        if (csvFile.exists()) {
            int result = JOptionPane.showConfirmDialog(gui.getMainFrame(), "File '" + csvFile.getName()
                    + "' already exists.\nDo you want to overwrite it?", "Overwrite?",
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);

            if (result != JOptionPane.OK_OPTION) {
                return;
            }
        }

        BufferedWriter writer = null;

        try {
            writer = new BufferedWriter(new FileWriter(csvFile));

            if (type == null) {
                // write the whole file
                CSVWriter.write(data, gui.getIntervalManager().getCurrentInterval(), writer);
            }
            else {
                CSVWriter.write(data, type, fields, gui.getIntervalManager().getCurrentInterval(), writer);
            }
        }
        catch (IOException ioe) {
            ioe.printStackTrace();
        }
        finally {
            if (writer != null) {
                try {
                    writer.close();
                }
                catch (IOException ioe2) {
                    // ignore
                }
            }
        }
    }
}
 
Example 20
Project: dawn-workflow   File: TelnetTransformer.java View source code Vote up 6 votes
private BufferedWriter write(FileInputStream fileInputStream, OutputStream outStream) throws Exception {
	
	final BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream, encoding.getExpression()));
	final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outStream, encoding.getExpression()));
	
	try {
		String line = null;
		while((line=reader.readLine())!=null) {
			logger.debug("Sending > "+line);
			writer.write(line);
			writer.newLine();
		}
	} finally {
		reader.close();
		writer.flush();
	}
	
	return writer;
}
 
Example 21
Project: java8-explorer   File: SiteCreator.java View source code Vote up 6 votes
public void createSite(ExplorerResult result) throws IOException {
    InputStream inputStream = getClass()
            .getClassLoader()
            .getResourceAsStream("template.html");

    Document document = Jsoup.parse(inputStream, "UTF-8", URI);
    Element contentList = document.body().getElementById("content-list");
    Element details = document.body().getElementById("details");


    List<TypeInfo> typeInfos = result.getTypeInfos();
    for (TypeInfo typeInfo : typeInfos) {
        StringBuilder listEntry = createListEntry(typeInfo);
        contentList.append(listEntry.toString());

        String detailView = createDetailView(typeInfo);
        details.append(detailView);
    }

    rewriteRelativeUrls(document);

    File file = new File("_site/index.html");
    BufferedWriter htmlWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
    htmlWriter.write(document.toString());
    htmlWriter.flush();
    htmlWriter.close();
}
 
Example 22
Project: k3po   File: RobotServerIT.java View source code Vote up 6 votes
@Test
public void shouldFinishEmptyOK() throws Exception {

    String path = "org/kaazing/robot/driver/emptyScript";
    // @formatter:off
    String strPrepared = "PREPARED\n" +
                         "content-length:0\n" +
                         "\n";
    String strExpected = "STARTED\n" +
                         "\n" +
                         "FINISHED\n" +
                         "content-length:0\n" +
                         "\n";
    // @formatter:on
    CharBuffer expectedPrepared = CharBuffer.wrap(strPrepared);
    CharBuffer expectedStartedAndFinished = CharBuffer.wrap(strExpected);

    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(control.getOutputStream()));
    out.append("PREPARE\n");
    out.append("version:2.0\n");
    out.append("name:" + path + "\n");
    out.append("\n");
    out.flush();

    BufferedReader in = new BufferedReader(new InputStreamReader(control.getInputStream()));

    CharBuffer prepared = CharBuffer.allocate(strPrepared.length());
    while (prepared.hasRemaining()) {
        in.read(prepared);
    }
    prepared.flip();

    assertEquals(expectedPrepared, prepared);

    out.append("START\n");
    out.append("\n");
    out.flush();

    CharBuffer startedAndFinished = CharBuffer.allocate(strExpected.length());
    while (startedAndFinished.hasRemaining()) {
        in.read(startedAndFinished);
    }
    startedAndFinished.flip();

    assertEquals(expectedStartedAndFinished, startedAndFinished);
    assertFalse(in.ready());
}
 
Example 23
Project: jlibs   File: BundleAnnotationProcessor.java View source code Vote up 6 votes
public void generateProperties(BufferedWriter props) throws IOException{
    Elements elemUtil = Environment.get().getElementUtils();
    for(Map.Entry<Element, Map<String, ExecutableElement>> methods : classes.entrySet()){
        writeComments(props, "-------------------------------------------------[ "+methods.getKey().getSimpleName()+" ]---------------------------------------------------");
        props.newLine();

        for(Map.Entry<String, ExecutableElement> entry : methods.getValue().entrySet()){
            String key = entry.getKey();
            ExecutableElement method = entry.getValue();

            String doc = elemUtil.getDocComment(method);
            String methodDoc = ModelUtil.getMethodDoc(doc);
            if(!StringUtil.isEmpty(methodDoc))
                writeComments(props, " "+methodDoc);

            int i = 0;
            Map<String, String> paramDocs = ModelUtil.getMethodParamDocs(doc);
            for(VariableElement param : method.getParameters()){
                String paramName = param.getSimpleName().toString();
                String paramDoc = paramDocs.get(paramName);
                if(StringUtil.isEmpty(paramDoc))
                    writeComments(props, " {"+i+"} "+paramName);
                else
                    writeComments(props, " {"+i+"} "+paramName+" ==> "+paramDoc);
                i++;
            }

            AnnotationMirror messageMirror = ModelUtil.getAnnotationMirror(method, Message.class);
            String value = ModelUtil.getAnnotationValue(method, messageMirror, "value");

            try{
                new MessageFormat(value);
            }catch(IllegalArgumentException ex){
                throw new AnnotationError(method, messageMirror, ModelUtil.getRawAnnotationValue(method, messageMirror, "value"), "Invalid Message Format: "+ex.getMessage());
            }

            NavigableSet<Integer> args = findArgs(value);
            int argCount = args.size()==0 ? 0 : (args.last()+1);
            if(argCount!=method.getParameters().size())
                throw new AnnotationError(method, "no of args in message format doesn't match with the number of parameters this method accepts");
            for(i=0; i<argCount; i++){
                if(!args.remove(i))
                    throw new AnnotationError(method, messageMirror, "{"+i+"} is missing in message");
            }

            writeProperty(props, key, value);
            props.newLine();
        }
    }
}
 
Example 24
Project: adc-wildner   File: AddTimeStampsToSequenceDatabase.java View source code Vote up 6 votes
/**
 * Read a sequence database in SPMF format, add timestamps and then 
 * write the sequence database to a file.
 * Note that this code could be further optimized if performance is an issue 
 * (instead of loading the file into memory, it could be loaded line by line).
 * @param inputFile the path of a sequence database in SPMF format
 * @param outputFile the output path for writing the database with timestamps
 * @throws IOException  if error while reading/writing file
 */
public void convert(String inputFile, String outputFile) throws IOException {
	// we create an object fro writing the output file
	BufferedWriter	writer = new BufferedWriter(new FileWriter(outputFile)); 
	
	SequenceDatabase database = new SequenceDatabase();
	database.loadFile(inputFile);
	
	BufferedReader myInput = null;
	try {
		for(int i=0; i < database.getSequences().size(); i++) {
			Sequence sequence = database.getSequences().get(i);

			// for each itemset in this sequence
			for(int j = 0; j< sequence.getItemsets().size(); j++) {
				// write timestamp
				writer.write("<" + j + "> ");
				
				Integer[] itemset = sequence.get(j);
				for(Integer item : itemset) {
					writer.write(item + " ");
				}
				writer.write("-1 ");
			}
			writer.write(" -2");
			// start a new line
			writer.newLine();
		}
		// close the output file
		writer.close();
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		if (myInput != null) {
			myInput.close();
		}
	}
}
 
Example 25
Project: socom   File: BatchCreate.java View source code Vote up 6 votes
private void createSocomConfigFile(BatchAccount member, String dirPath) throws IOException {
	
	File outFile = new File(dirPath+"\\socom_"+member.getGroupID()+""+member.getSocomID()+""+member.getName().replaceAll(" ", "")+".cfg");
	
	String outfileName = outFile.getAbsolutePath();
	int i = outfileName.lastIndexOf('.');
	String useName = outfileName;
	int j=2;
	while (outFile.exists())
	{
		if (i == -1 || i == outfileName.length()-1)	useName = outfileName+"_"+j;
		else useName = outfileName.substring(0,i)+"_"+j+"."+outfileName.substring(i+1);
		outFile = new File(useName);
		j++;
	}
	
	BufferedWriter writer = null;
	try
	{
		writer = new BufferedWriter(new FileWriter(outFile));
		writer.append("{\n");
		writer.append("\t\"server\": \"ktxsoftware.com\",\n");
		writer.append("\t\"username\": \""+member.getName()+"\",\n");
		writer.append("\t\"password\": \""+member.getPassword()+"\"\n");
		writer.append("}");
		writer.flush();
	}
	finally 
	{
		writer.close();
	}				
}
 
Example 26
Project: visuwall   File: ZooInspectorManagerImpl.java View source code Vote up 6 votes
public void saveNodeViewersFile(File selectedFile,
        List<String> nodeViewersClassNames) throws IOException {
    if (!selectedFile.exists()) {
        if (!selectedFile.createNewFile()) {
            throw new IOException(
                    "Failed to create node viewers configuration file: "
                            + selectedFile.getAbsolutePath());
        }
    }
    FileWriter writer = new FileWriter(selectedFile);
    try {
        BufferedWriter buff = new BufferedWriter(writer);
        try {
            for (String nodeViewersClassName : nodeViewersClassNames) {
                buff.append(nodeViewersClassName);
                buff.append("\n");
            }
        } finally {
            buff.flush();
            buff.close();
        }
    } finally {
        writer.close();
    }
}
 
Example 27
Project: tdq-studio-se   File: ModelIndicatorTdColumnToModelElementTask.java View source code Vote up 6 votes
/**
 * 
 * DOC mzhao string replacement method.
 * 
 * @param srcFile
 * @return
 */
private void replace(File srcFile) throws Throwable {
    File destFile = new File(srcFile.getAbsolutePath() + MIGRATION_FILE_EXT);

    BufferedReader fileReader = new BufferedReader(new FileReader(srcFile));
    BufferedWriter fileWriter = new BufferedWriter(new FileWriter(destFile));

    while (fileReader.ready()) {
        String line = fileReader.readLine();
        if (StringUtils.contains(line, TO_BE_RPLACED_STRING_PREFIX) && !StringUtils.contains(line, REPLACED_STRING)) {
            line = StringUtils.replace(line, TO_BE_RPLACED_STRING_PREFIX, TO_BE_RPLACED_STRING_PREFIX + REPLACED_STRING); 
            log.debug(line);
        }
        fileWriter.append(line);
        fileWriter.newLine();
    }
    fileWriter.flush();
    fileWriter.close();
    fileWriter = null;
    fileReader.close();
    fileReader = null;
}
 
Example 28
Project: RoboRunner   File: BattleRunner.java View source code Vote up 6 votes
@Override
public String call() throws Exception {
  final long startTime = System.nanoTime();
  Process battleProcess = _processQueue.poll();
  BufferedWriter writer = new BufferedWriter(
      new OutputStreamWriter(battleProcess.getOutputStream()));
  BufferedReader reader = new BufferedReader(
      new InputStreamReader(battleProcess.getInputStream()));
  BotList botList;
  if (_selector == null) {
    botList = _botList;
  } else {
    botList = _callbackPool.submit(new Callable<BotList>() {
      @Override
      public BotList call() throws Exception {
        return _selector.nextBotList();
      }
    }).get();
  }
  writer.append(COMMA_JOINER.join(botList.getBotNames()) + "\n");
  writer.flush();
  String input;
  do {
    // TODO: How to handle other output, errors etc?
    input = reader.readLine();
  } while (!isBattleResult(input));
  final String result = input;
  _processQueue.add(battleProcess);
  _callbackPool.submit(new Runnable() {
    @Override
    public void run() {
      _listener.processResults(
          getRobotScoreList(result), System.nanoTime() - startTime);
    }
  }).get();
  return result;
}
 
Example 29
Project: gundog-engine   File: Balancer.java View source code Vote up 6 votes
private static void writeTitle(BufferedWriter writer) throws IOException {
	String date = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(
			new Date(System.currentTimeMillis()));
	writer.append(date + ",");
	for (int levelTwo = STARTING_LEVEL; levelTwo <= MAX_LEVEL; levelTwo *= 10) {
		for (int racesTwo : Races.ALL_RACES) {
			writer.append(Races.toString(racesTwo) + "_" + levelTwo + ",");
		}
	}
	writer.append("\n");
}
 
Example 30
Project: grap   File: EsriGRIDWriter.java View source code Vote up 5 votes
public void save() {

		try {

			FileWriter f = new FileWriter(fileName);
			BufferedWriter fout = new BufferedWriter(f);
			DecimalFormat df = new DecimalFormat("##.###");
			df.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
			df.setDecimalSeparatorAlwaysShown(true);

			int ncols = rasterMetadata.getNCols();
			int nrows = rasterMetadata.getNRows();

			fout.write("ncols " + Integer.toString(ncols));
			fout.newLine();
			fout.write("nrows " + Integer.toString(nrows));
			fout.newLine();
			fout.write("xllcorner "
					+ Double.toString(rasterMetadata.getEnvelope().getMinX()));
			fout.newLine();
			fout.write("yllcorner "
					+ Double.toString(rasterMetadata.getEnvelope().getMinY()));
			fout.newLine();
			fout.write("cellsize "
					+ Double.toString(rasterMetadata.getPixelSize_X()));
			fout.newLine();
			fout.write("nodata_value "
					+ Double.toString(rasterMetadata.getNoDataValue()));
			fout.newLine();

			if (grapImagePlus.getType() != ImagePlus.COLOR_RGB) {
				for (int i = 0; i < nrows; i++) {
					for (int j = 0; j < ncols; j++) {

						float dValue = grapImagePlus.getProcessor()
								.getPixelValue(j, i);

						if (Float.isNaN(dValue)) {
							fout.write(df.format(-9999f) + " ");
						} else {
							fout.write(df.format(dValue) + " ");
						}
					}
					fout.newLine();
				}
			}
			fout.close();
			f.close();

		} catch (Exception e) {
		}

	}
 
Example 31
Project: ArubaSyslog   File: MainActivity.java View source code Vote up 5 votes
public void ExportToCSV(Cursor c, String fileName) {

        int rowCount = 0;
        int colCount = 0;
        FileWriter fw;
        BufferedWriter bfw;
        String sdCardDir = Environment.getExternalStorageDirectory()
                .getAbsolutePath()+"/"+fileName;

        File saveFile = new File(sdCardDir);
        try {

            rowCount = c.getCount();
            colCount = c.getColumnCount();
            fw = new FileWriter(saveFile);
            bfw = new BufferedWriter(fw);
            if (rowCount > 0) {
                c.moveToFirst();
                // ????
                for (int i = 0; i < colCount; i++) {
                    if (i != colCount - 1)
                        bfw.write(c.getColumnName(i) + ',');
                    else
                        bfw.write(c.getColumnName(i));
                }
                // ???????
                bfw.newLine();
                // ????
                for (int i = 0; i < rowCount; i++) {
                    c.moveToPosition(i);
                    // Toast.makeText(mContext, "?????"+(i+1)+"?",
                    // Toast.LENGTH_SHORT).show();
                    Log.v("????", "?????" + (i + 1) + "?");
                    for (int j = 0; j < colCount; j++) {
                        if (j != colCount - 1)
                            bfw.write(c.getString(j) + ',');
                        else
                            bfw.write(c.getString(j));
                    }
                    // ?????????
                    bfw.newLine();
                }
            }
            // ?????????
            bfw.flush();
            // ????
            bfw.close();
            // Toast.makeText(mContext, "?????", Toast.LENGTH_SHORT).show();
            Log.v("????", "?????");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            c.close();
        }
    }
 
Example 32
Project: strongback-java   File: LogDecoder.java View source code Vote up 5 votes
private static final void decode(DataInputStream in, BufferedWriter writer)
        throws BadFileFormatException, EOFException, IOException {
    // Verify Header
    printer.print(Strings.CHECK_LOG, Printer.Verbosity.VERBOSE);
    byte[] header = new byte[3];
    in.read(header);
    if(!Arrays.equals(header, "log".getBytes())) throw new BadFileFormatException();
    printer.print(Strings.SUCCESS, Printer.Verbosity.VERBOSE);

    // Get the number of elements
    int numElements = in.read();
    printer.print(Strings.ELEMENT_COUNT + numElements, Printer.Verbosity.VERBOSE);

    // Get the size of each element
    int[] elementSizes = new int[numElements];
    for(int i = 0; i< elementSizes.length; i++) {
        elementSizes[i] = in.read();
    }

    // Write the name of each element
    for(int i = 0; i< numElements; i++) {
        int nameSize = in.read();
        byte[] b = new byte[nameSize];
        in.read(b);
        writer.write(new String(b) + ", ");
    }
    writer.newLine();

    printer.print(Strings.READING_LOG, Printer.Verbosity.VERBOSE);
    int lineCount = 0;
    // Read each record
    try {
        in.mark(4);
        while(in.readInt()!=0xFFFFFFFF) {
            printer.print(Strings.READ_LINE + lineCount, Printer.Verbosity.VERBOSE);
            in.reset();
            for(int i = 0; i < numElements; i++) {
                if(elementSizes[i]==4){
                    writer.write(in.readInt() + ", ");
                }
                else if(elementSizes[i]==2)
                    writer.write(in.readShort() + ", ");
            }
            writer.newLine();
            lineCount++;
            in.mark(4);
        }
        printer.print(Strings.SUCCESS, Printer.Verbosity.VERBOSE);
    } finally {
        // Always flush what we were able to decode
        printer.print(Strings.FLUSH_FILES, Printer.Verbosity.VERBOSE);
        writer.flush();
    }
}
 
Example 33
Project: eadventure   File: ResourcesGenerator.java View source code Vote up 5 votes
public static void main(String args[]) throws IOException {
	File fromModule = new File(PREFIX_FROM_MODULE);
	File fromRoot = new File(PREFIX_FROM_ROOT);
	File from = null;
	if (fromModule.isDirectory()) {
		from = fromModule;
	} else if (fromRoot.isDirectory()) {
		from = fromRoot;
	} else {
		throw new IOException("Cannot build R-file: bad relative paths");
	}
	File f = new File(from, "java/" + PACKAGE + "/R.java");

	System.err.println("Writing R file to '" + f.getAbsolutePath() + "'");
	BufferedWriter writer = null;
	try {
		boolean created = f.exists();
		if (!created) {
			created = f.createNewFile();
		}

		if (created) {
			writer = new BufferedWriter(new FileWriter(f));
			writer.write("package " + PACKAGE.replace('/', '.') + ";");
			writer.newLine();
			writer.newLine();
			writer.write("public class R {");
			writer.newLine();
			writer.write("public static final String[]"
					+ " RESOURCES = new String[]{");
			writer.newLine();

			ArrayList<File> resources = getResources(from);
			for (int i = 0; i < resources.size(); i++) {
				File file = resources.get(i);
				String name = file.getAbsolutePath().replace('\\', '/');
				name = name.substring(name.indexOf(PACKAGE));
				writer.write("  \"" + name + "\""
						+ (i == resources.size() - 1 ? "" : ","));
				writer.newLine();
			}
			writer.write("};");
			writer.newLine();
			writer.write("}");
		} else {
			System.err.println("R-file couldn't be created.");
		}

	} catch (IOException e) {
		System.err.println("Error creating R-file: " + e.getMessage());
	} finally {
		if (writer != null) {
			try {
				writer.close();
			} catch (IOException e1) {
				System.err.println(e1.getMessage());
			}
		}

	}
}