Java Code Examples for java.io.BufferedWriter.close()

The following are Jave code examples for showing how to use close() of the java.io.BufferedWriter class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: hadoop   File: TestQueue.java   View Source Code Vote up 7 votes
/**
* write cofiguration
* @return
* @throws IOException
*/
 private File writeFile() throws IOException {

   File f = new File(testDir, "tst.xml");
   BufferedWriter out = new BufferedWriter(new FileWriter(f));
   String properties = "<properties><property key=\"key\" value=\"value\"/><property key=\"key1\" value=\"value1\"/></properties>";
   out.write("<queues>");
   out.newLine();
   out.write("<queue><name>first</name><acl-submit-job>user1,user2 group1,group2</acl-submit-job><acl-administer-jobs>user3,user4 group3,group4</acl-administer-jobs><state>running</state></queue>");
   out.newLine();
   out.write("<queue><name>second</name><acl-submit-job>u1,u2 g1,g2</acl-submit-job>"
       + properties + "<state>stopped</state></queue>");
   out.newLine();
   out.write("</queues>");
   out.flush();
   out.close();
   return f;

 }
 
Example 2
Project: FacetExtract   File: hUpperMerge.java   View Source Code Vote up 6 votes
public static void writetxt(String txtPath, String txtCont)
{
	try
	{
		File f = new File(txtPath);
		if (!f.exists())
		{
			f.createNewFile();
		}
		OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f,true), "UTF-8");
		BufferedWriter writer = new BufferedWriter(write);
		writer.write(txtCont);
		writer.close();
	} catch (Exception e)
	{
		e.printStackTrace();
	}
}
 
Example 3
Project: hadoop   File: TestLocalRunner.java   View Source Code Vote up 6 votes
/**
 * Create a single input file in the input directory.
 * @param dirPath the directory in which the file resides
 * @param id the file id number
 * @param numRecords how many records to write to each file.
 */
private void createInputFile(Path dirPath, int id, int numRecords)
    throws IOException {
  final String MESSAGE = "This is a line in a file: ";

  Path filePath = new Path(dirPath, "" + id);
  Configuration conf = new Configuration();
  FileSystem fs = FileSystem.getLocal(conf);

  OutputStream os = fs.create(filePath);
  BufferedWriter w = new BufferedWriter(new OutputStreamWriter(os));

  for (int i = 0; i < numRecords; i++) {
    w.write(MESSAGE + id + " " + i + "\n");
  }

  w.close();
}
 
Example 4
Project: MyFire   File: LogUtils.java   View Source Code Vote up 6 votes
/**
 * 打开日志文件并写入日志
 *
 * @return
 **/
private synchronized static void log2File(String mylogtype, String tag, String text) {
    Date nowtime = new Date();
    String date = FILE_SUFFIX.format(nowtime);
    String dateLogContent = LOG_FORMAT.format(nowtime) + ":" + mylogtype + ":" + tag + ":" + text; // 日志输出格式
    File destDir = new File(LOG_FILE_PATH);
    if (!destDir.exists()) {
        destDir.mkdirs();
    }
    File file = new File(LOG_FILE_PATH, LOG_FILE_NAME + date);
    try {
        FileWriter filerWriter = new FileWriter(file, true);
        BufferedWriter bufWriter = new BufferedWriter(filerWriter);
        bufWriter.write(dateLogContent);
        bufWriter.newLine();
        bufWriter.close();
        filerWriter.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 5
Project: ibench   File: ConfigGenerator.java   View Source Code Vote up 6 votes
public String generateConfigFile(boolean noOutput) throws IOException
{
	String _configName = "config" + _counter + ".txt";
	_outDir = "out" + _counter;
	_counter++;
	
	BufferedWriter configWriter = new BufferedWriter(new FileWriter(_configPath + _configName));

	generatePreambleAndOutputPaths(configWriter);
	generateScenarioRepetitions(configWriter);
	generateParameters(configWriter);
	generateDeviations(configWriter);
	generateRandomsAndMappingLang(configWriter);
	generateOutputActivation(configWriter, noOutput);
	generateTrampOutputActivation(configWriter);

	configWriter.close();
	
	return _configName;
}
 
Example 6
Project: Panako   File: SyncSinkFrame.java   View Source Code Vote up 6 votes
public void modifyCSVFile(File csvFile,File shiftedCSVFile,double shift) throws IOException{
	
	if (!csvFile.exists()) {
		throw new IllegalArgumentException("File '" + csvFile + "' does not exist");
	}
	
	FileReader fileReader = new FileReader(csvFile);
	BufferedReader in = new BufferedReader(fileReader);
	
	FileWriter fileWriter = new FileWriter(shiftedCSVFile);
	BufferedWriter out = new BufferedWriter(fileWriter);
	
	String inputLine = in.readLine();	
	while (inputLine != null) {
		final String[] row = inputLine.split(",");
		if (!inputLine.trim().isEmpty() && row.length > 1) {
			double timeInSeconds = Double.valueOf(row[0]);
			double shiftedTime = timeInSeconds + shift;
			String outputLine = String.format("%.4f" , shiftedTime)  + inputLine.substring(row[0].length(), inputLine.length()) + System.lineSeparator();
			out.write(outputLine);
		}
		inputLine = in.readLine();
	}
	out.close();
	in.close();
}
 
Example 7
Project: smaph   File: ExampleGatherer.java   View Source Code Vote up 6 votes
public void dumpExamplesLibSvm(String filename, FeatureNormalizer fn, int[] selectedFeatures) throws IOException {
	BufferedWriter wr = new BufferedWriter(new FileWriter(filename, false));

	for (int i = 0; i < featureVectorsAndTargetGroups.size(); i++){
		List<String> vectors = new Vector<String>();
		
		for (Pair<FeaturePack<T>, Double> vectAndGold : featureVectorsAndTargetGroups.get(i))
			vectors.add(writeLineLibSvm(fn.ftrToNormalizedFtrArray(vectAndGold.first), wr, vectAndGold.second, i, selectedFeatures));

		//This is just to make sure that lines are output always in the same order. (It seems that vector order does change the resulting model with some libraries.)
		Collections.sort(vectors);
		
		for (String vectorLine: vectors){
			wr.write(vectorLine);
			wr.write("\n");
		}
	}			
	wr.close();
}
 
Example 8
Project: aliyun-maxcompute-data-collectors   File: TestExport.java   View Source Code Vote up 5 votes
/**
 * Create a data file that gets exported to the db.
 * @param fileNum the number of the file (for multi-file export)
 * @param numRecords how many records to write to the file.
 * @param gzip is true if the file should be gzipped.
 */
protected void createTextFile(int fileNum, int numRecords, boolean gzip,
    ColumnGenerator... extraCols) throws IOException {
  int startId = fileNum * numRecords;

  String ext = ".txt";
  if (gzip) {
    ext = ext + ".gz";
  }
  Path tablePath = getTablePath();
  Path filePath = new Path(tablePath, "part" + fileNum + ext);

  Configuration conf = new Configuration();
  if (!BaseSqoopTestCase.isOnPhysicalCluster()) {
    conf.set(CommonArgs.FS_DEFAULT_NAME, CommonArgs.LOCAL_FS);
  }
  FileSystem fs = FileSystem.get(conf);
  fs.mkdirs(tablePath);
  OutputStream os = fs.create(filePath);
  if (gzip) {
    CompressionCodecFactory ccf = new CompressionCodecFactory(conf);
    CompressionCodec codec = ccf.getCodec(filePath);
    os = codec.createOutputStream(os);
  }
  BufferedWriter w = new BufferedWriter(new OutputStreamWriter(os));
  for (int i = 0; i < numRecords; i++) {
    w.write(getRecordLine(startId + i, extraCols));
  }
  w.close();
  os.close();

  if (gzip) {
    verifyCompressedFile(filePath, numRecords);
  }
}
 
Example 9
Project: AndroidGeneralUtils   File: BLog.java   View Source Code Vote up 5 votes
private static synchronized void forceWriteToFile(String string) {

        try {
            FileWriter fstream = new FileWriter(Environment.getExternalStorageDirectory() + File.separator + sFileName, true);
            BufferedWriter fbw = new BufferedWriter(fstream);
            fbw.write("\n\n" + string);
            fbw.newLine();
            fbw.close();
        } catch (Throwable e) {
            e.printStackTrace();
        }

    }
 
Example 10
Project: Backmemed   File: FileManager.java   View Source Code Vote up 5 votes
public void saveWaypoints()
{
	try
	{
		File file = new File(xdolfDir.getAbsolutePath(), "waypoints.txt");
		BufferedWriter out = new BufferedWriter(new FileWriter(file));
		for(Waypoint wayPoint : Waypoint.wayPoints)
		{
			out.write(wayPoint.getName() + ":" + (int)wayPoint.getX() + ":" + (int)wayPoint.getY() + ":" + (int)wayPoint.getZ());
			out.write("\r\n");
		}
		out.close();
	}catch(Exception e) {}
}
 
Example 11
Project: PIQEDia   File: CreateWiffToMzxmlmp.java   View Source Code Vote up 5 votes
private static void writeTxtFile( File outputDir ) {
	String MSGFBatFilePath = outputDir.toString() + "\\WiffToMzxmlcmds.txt";
	try {
		BufferedWriter bufwriter = new BufferedWriter( new FileWriter(MSGFBatFilePath) );
		bufwriter.write(WiffMzmlBatFile.toString());
		bufwriter.close();
	} catch( Exception e ) {
		e.printStackTrace();
	}
}
 
Example 12
Project: openjdk-jdk10   File: StreamLinesTest.java   View Source Code Vote up 5 votes
static void writeLineSeparator(Path p,
                               IntFunction<LineSeparator> lineSeparatorGenerator,
                               int lines, Charset cs) throws IOException {
    BufferedWriter bw = Files.newBufferedWriter(p, cs, StandardOpenOption.APPEND);
    bw.write(lineSeparatorGenerator.apply(lines - 1).value);
    bw.flush();
    bw.close();
}
 
Example 13
Project: hanlpStudy   File: TestICWB.java   View Source Code Vote up 5 votes
public void testDumpPeople2014ToBEMS() throws Exception
{
    final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("D:\\Tools\\CRF++-0.58\\example\\seg_cn\\2014.txt")));
    CorpusLoader.walk("D:\\JavaProjects\\CorpusToolBox\\data\\2014", new CorpusLoader.Handler()
    {
        @Override
        public void handle(Document document)
        {
            List<List<Word>> simpleSentenceList = document.getSimpleSentenceList();
            for (List<Word> wordList : simpleSentenceList)
            {
                try
                {
                    for (Word word : wordList)
                    {

                        bw.write(word.value);
                        bw.write(' ');

                    }
                    bw.newLine();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
    });
    bw.close();
}
 
Example 14
Project: AutoDnaCode   File: AutoCodeUtil.java   View Source Code Vote up 5 votes
public static void writeIntoFile(File file ,  String text , String charset){
    try {
        FileOutputStream outputStream = new FileOutputStream(file);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, charset);
        BufferedWriter bufferWritter = new BufferedWriter(outputStreamWriter);
        bufferWritter.write(text);
        bufferWritter.close();
        outputStreamWriter.close();
        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 15
Project: geomapapp   File: XMap.java   View Source Code Vote up 5 votes
protected void doZoomHistory(String past, String next) throws IOException {

		if (app instanceof MapApp) {
			if(((MapApp) app).historyFile.exists()) {
				((MapApp) app).startNewZoomHistory();
			}

			if(((MapApp) app).historyFile.canWrite()) {
				BufferedWriter bw = new BufferedWriter(new FileWriter(((MapApp) app).historyFile.getAbsoluteFile(), false));
				bw.write(past + "\n");
				bw.write(next);
				bw.close();
			}
		}
	}
 
Example 16
Project: revolution-irc   File: CommandAliasManager.java   View Source Code Vote up 5 votes
public boolean saveUserSettings() {
    try {
        BufferedWriter writer = new BufferedWriter(new FileWriter(
                new File(mContext.getFilesDir(), ALIASES_PATH)));
        saveUserSettings(writer);
        writer.close();
        return true;
    } catch (IOException ignored) {
    }
    return false;
}
 
Example 17
Project: CVPR_paper_search_tool   File: Crawler.java   View Source Code Vote up 5 votes
public boolean OutputTitles(String filename)
{
	logMessage = "OutputTitle:<br/>";
	logger.info("OutputTitle()...");

	try
	{
		File corpus=new File(filename);
		BufferedWriter writer = new BufferedWriter(new FileWriter(corpus));

		List<Paper> papers = Paper.list();
		
		for (int i = 0; i < papers.size(); i++) 
		{
			Paper paper = papers.get(i);

			if( paper.pdf_text!=null && paper.pdf_text.length() > 0 )
			{
			    writer.write (paper.title.trim()+" <eop> ");
			}
	    }

		writer.close();
	}
	catch(Exception e)
	{
		logMessage += "Error:" + e.getMessage();
		e.printStackTrace();
	}
    
	return true;
}
 
Example 18
Project: Projeto-IP2   File: DisciplinaDAO.java   View Source Code Vote up 5 votes
public void escreveNextId () throws IOException {
	File arquivo = new File("IdDisciplina.dat");
	FileWriter fw = new FileWriter(arquivo);
	BufferedWriter bw = new BufferedWriter(fw);
	bw.write(String.valueOf(nextId));
	bw.close();
	fw.close();
}
 
Example 19
Project: spring-i18n-support   File: PropertiesWriter.java   View Source Code Vote up 4 votes
public void writeProperties(List<MessageResourceEntry> entries,
							Locale locale,
							BufferedWriter writer,
							String encoding) throws I18nException
{
	try
	{
		writer.write("#Generated File by i18n PropertiesWriter.");
		writer.newLine();
		writer.write("#Copyright 2012 Namics AG. All rights reserved.");
		writer.newLine();
		writer.write("#Generation date: " + new Date().toString());
		writer.newLine();
		for (MessageResourceEntry entry : entries)
		{
			String value = this.getOptimizedValue(entry, locale);
			writer.newLine();
			writer.write(entry.getCodeId());
			writer.write("=");
			writer.write(value);
		}
	}
	catch (IOException e1)
	{
		LOG.error("IOException occured. {}", e1);
		throw new I18nException(e1);
	}
	finally
	{
		if (writer != null)
		{
			try
			{
				writer.flush();
				writer.close();
			}
			catch (IOException e)
			{
				LOG.error("Could not close writer. {}", e);
			}
		}
	}
}
 
Example 20
Project: Achtbaan   File: ConfigManager.java   View Source Code Vote up 4 votes
public void setHeader(File file, String[] header) {
    if (!file.exists())
        return;

    try {
        String currentLine;
        StringBuilder config = new StringBuilder("");
        BufferedReader reader = new BufferedReader(new FileReader(file));

        while ((currentLine = reader.readLine()) != null)
            config.append(currentLine + "\n");

        reader.close();
        config.append("# +----------------------------------------------------+ #\n");

        for (String line : header) {
            if (line.length() > 50)
                continue;

            int lenght = (50 - line.length()) / 2;
            StringBuilder finalLine = new StringBuilder(line);

            for (int i = 0; i < lenght; i++) {
                finalLine.append(" ");
                finalLine.reverse();
                finalLine.append(" ");
                finalLine.reverse();
            }

            if (line.length() % 2 != 0)
                finalLine.append(" ");

            config.append("# < " + finalLine.toString() + " > #\n");
        }
        config.append("# +----------------------------------------------------+ #");

        BufferedWriter writer = new BufferedWriter(new FileWriter(file));
        writer.write(this.prepareConfigString(config.toString()));
        writer.flush();
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}