Java Code Examples for java.io.FileWriter

The following are top voted examples for showing how to use java.io.FileWriter. 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 generate more good examples.
Example 1
Project: NavyCraft2-Lite   File: CraftMover.java   View source code 8 votes vote down vote up
public static void battleLogger(String str) {

		String path = File.separator + "BattleLog.txt";
		File file = new File(path);
		try {
			FileWriter fw = new FileWriter(file.getName(), true);
			BufferedWriter bw = new BufferedWriter(fw);

			Date now = new Date();
			bw.write(DateFormat.getDateInstance(DateFormat.SHORT).format(now) + " " + DateFormat.getTimeInstance().format(now) + " - " + str);
			bw.newLine();

			bw.flush();
			bw.close();
		} catch (Exception e) {
			System.out.println("Battle log failure");
		}
	}
 
Example 2
Project: ZooKeeper   File: ZooInspectorManagerImpl.java   View source code 7 votes vote down vote up
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 3
Project: NewKakaoBot   File: FileManager.java   View source code 7 votes vote down vote up
public void removeData(String path, String key) {
    createFile(path);

    try {
        BufferedReader reader = new BufferedReader(new FileReader(new File(KAKAOBOT_HOME, path)));

        String line;
        StringBuilder result = new StringBuilder();
        while((line = reader.readLine()) != null) {
            result.append(line);
            result.append("\n");
        }

        JSONObject json = new JSONObject(result.toString() + "");
        json.remove(key);

        BufferedWriter writer = new BufferedWriter(new FileWriter(new File(KAKAOBOT_HOME, path)));

        writer.write(json.toString());

        reader.close();
        writer.close();
    } catch(IOException err) {
        err.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
 
Example 4
Project: hadoop-oss   File: TestConfiguration.java   View source code 6 votes vote down vote up
public void testCompactFormat() throws IOException {
  out=new BufferedWriter(new FileWriter(CONFIG));
  startConfig();
  appendCompactFormatProperty("a", "b");
  appendCompactFormatProperty("c", "d", true);
  appendCompactFormatProperty("e", "f", false, "g");
  endConfig();
  Path fileResource = new Path(CONFIG);
  Configuration conf = new Configuration(false);
  conf.addResource(fileResource);

  assertEquals("b", conf.get("a"));

  assertEquals("d", conf.get("c"));
  Set<String> s = conf.getFinalParameters();
  assertEquals(1, s.size());
  assertTrue(s.contains("c"));

  assertEquals("f", conf.get("e"));
  String[] sources = conf.getPropertySources("e");
  assertEquals(2, sources.length);
  assertEquals("g", sources[0]);
  assertEquals(fileResource.toString(), sources[1]);
}
 
Example 5
Project: MARF-for-Android   File: SyntaxError.java   View source code 6 votes vote down vote up
/**
 * Serialization routine.
 * TODO: migrate to MARF dump/restore mechanism.
 *
 * @param piOperation  0 for load (not implemented), 1 for save as text
 * @param poFileWriter writer to write the error message to
 * @return <code>true</code> if the operation was successful
 */
public boolean serialize(int piOperation, FileWriter poFileWriter) {
    if (piOperation == 0) {
        // TODO load
        System.err.println("LexicalError::serialize(LOAD) - unimplemented");
        return false;
    } else {
        try {
            poFileWriter.write
                    (
                            "Syntax Error (line " + this.iLineNo + "): " + this.iCurrentErrorCode +
                                    " - " + this.strMessage + ", " +
                                    "faulting token: [" + this.oFaultingToken.getLexeme() + "]\n"
                    );

            return true;
        } catch (IOException e) {
            System.err.println("SyntaxError::serialize() - " + e.getMessage());
            e.printStackTrace(System.err);
            return false;
        }
    }
}
 
Example 6
Project: integrations   File: ConvertImages.java   View source code 6 votes vote down vote up
public static void main( String[] args ) throws IOException {
    if ( args.length != 2 ) {
        System.err.println( "Expected usage is ./ConvertImages inputDirectory outputCsvFile" );
    }
    File directory = new File( args[ 0 ] );
    File outputFile = new File( args[ 1 ] );
    FileWriter writer = new FileWriter( outputFile );

    writer.write("XREF,mugshot\n" );

    if ( directory.isDirectory() ) {
        for ( File file : directory.listFiles() ) {
            if ( file.isFile() && isImage( file.getCanonicalPath() ) ) {
                writer.write( new StringBuilder( getXref( file.getName() ) ).append( "," )
                        .append( encoder.encodeToString( Files.readAllBytes( file.toPath() ) ) ).append( "\n" )
                        .toString() );

            }
        }
    }
    writer.flush();
    writer.close();
}
 
Example 7
Project: incubator-netbeans   File: TopLoggingOwnConfigTest.java   View source code 6 votes vote down vote up
protected void setUp() throws Exception {
    clearWorkDir();

    System.setProperty("netbeans.user", getWorkDirPath());

    log = new File(getWorkDir(), "own.log");
    File cfg = new File(getWorkDir(), "cfg");

    FileWriter w = new FileWriter(cfg);
    w.write("handlers=java.util.logging.FileHandler\n");
    w.write(".level=100\n");
    w.write("java.util.logging.FileHandler.pattern=" + log.toString().replace('\\', '/') +"\n");
    w.close();


    System.setProperty("java.util.logging.config.file", cfg.getPath());

    // initialize logging
    TopLogging.initialize();
}
 
Example 8
Project: lembredio   File: Farmaceutico.java   View source code 6 votes vote down vote up
public boolean verificaFarmacia() throws FileNotFoundException, IOException{
    File file = new File("FarmaciasCadastradas.txt");
    if(!file.exists()) file.createNewFile();
    InputStream is = new FileInputStream("FarmaciasCadastradas" +".txt");
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String linha;
    do{
        linha = br.readLine();
        if(linha== null) break;
        if(linha.equals(nomeFarmacia)) return true;
        
    }while(linha != null);
    FileWriter outputfile = new FileWriter(file, true);
    PrintWriter out = new PrintWriter(outputfile);
    System.out.println(nomeFarmacia);
    out.println(nomeFarmacia);
    out.flush();
    out.close();
    return false;
}
 
Example 9
Project: cockroach   File: NameStore.java   View source code 6 votes vote down vote up
@Override
public void store(TaskResponse response) throws IOException {
    PrintWriter writer = new PrintWriter(new FileWriter("D://"+id+".txt",true),true);
    Elements els = response.select("strong");
    els.stream().map(el -> el.text().trim())
            .filter(name -> !name.contains("第"))
            .filter(name -> !name.startsWith("热门"))
            .filter(name -> !name.startsWith("找动画"))
            .filter(name -> !name.startsWith("凹凸"))
            .filter(name -> !name.contains("更多"))
            .filter(name -> !name.contains("5068"))
            .filter(name -> !name.contains("热播动画"))
            .filter(name -> !name.contains("点击浏览"))
            .filter(name -> !name.contains("上一页"))
            .filter(name -> !name.contains("关于我们"))
            .filter(name -> name.length() > 0)
            .map(name -> name.split("(")[0].trim().replaceAll(" ",""))
            .forEach(name -> {
                System.out.println(id+":"+name);
                writer.println(name);
            });
    writer.close();
}
 
Example 10
Project: ATEBot   File: Main.java   View source code 6 votes vote down vote up
public static void saveConfig(){
 	try{
  	GsonBuilder builder = new GsonBuilder();
  	Gson gson = builder.setPrettyPrinting().enableComplexMapKeySerialization().create();
Map<String, Object> hm = new HashMap<String, Object>();
hm.put("token", token);
hm.put("webNumThreads", webNumThreads);
hm.put("playinformation", playinformation);
hm.put("webPort", webPort);
hm.put("accounts", accounts);
hm.put("messages", messages);
  	
Writer writer = new FileWriter("botsetting.json");
gson.toJson(hm, writer);
writer.close();
 	}catch (Exception e) {}
 }
 
Example 11
Project: PekaED   File: EpisodePanel.java   View source code 6 votes vote down vote up
public void saveEpisode() {
	try {
		BufferedWriter w = new BufferedWriter(new FileWriter(Data.currentEpisodePath + File.separatorChar + Data.currentEpisodeFile.getName()));
		
		w.write(Data.currentEpisodeName + "\n");
		w.write(Data.currentEpisodePath + "\n");
		
		for (File f : Data.episodeFiles) {
			w.write(f.getAbsolutePath() + "\n");
		}
		
		w.flush();
		w.close();
		
		Data.episodeChanged = false;
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example 12
Project: Soup   File: HTMLGen.java   View source code 6 votes vote down vote up
/**
 * Generates HTML documentation for the Soup session
 * @param title title on the window
 * @param description the header of the page
 * @throws IOException throws if it cannot store
 */
public static void generateOutputDocumentation(String title, String description) throws IOException {
	try {
		FileWriter f = new FileWriter(System.getProperty("user.dir") + "\\" + "SoupNoodle.html");
	
		f.write("<style>h1 {	color: blue;}p {	color: red;}div {	display: flex;	align-items: center;	justify-content: center;	flex-direction: column;}</style><title>");
		f.write(title);
		f.write("</title><center><h1>");
		f.write(description + " [" + LocalTime.now().getHour() + ":" + LocalTime.now().getMinute() + "]");
		f.write("</h1></center><div><p>Local Vars</p><ul>");
		writeVars(f);
		f.write("</ul><p>Outputs</p><ul>");
		writeOutputs(f);
		f.write("</ul></div><div><p>Questions Asked</p><ul>");
		writeQuestions(f);
		f.write("</ul></div>");
		f.close();
		System.out.println("Output Generated at " + System.getProperty("user.dir") + "\\" + "SoupNoodle.html");
	}
	catch (IOException ex) {
		System.out.println("Error storing output documentation at " + System.getProperty("user.dir") + "\\" + "SoupNoodle.html");
	}
}
 
Example 13
Project: ibench   File: HTMLPresenter.java   View source code 6 votes vote down vote up
/**
 * Prints the buffer (which should be in HTML) in a file which will serve
 * for the browser by putting before and after the HTML headers
 */
public void printInHtmlFile(StringBuffer buf, String pathPrefix, String file)
{

    StringBuffer fbuf = new StringBuffer();
    printHTMLHeader(fbuf);
    fbuf.append(buf);
    printHTMLFooter(fbuf);
    try
    {
        BufferedWriter bufWriter = new BufferedWriter(new FileWriter(new File(pathPrefix, file)));
        bufWriter.write(fbuf.toString());
        bufWriter.close();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }

}
 
Example 14
Project: easy-test   File: FindNotMakeTest.java   View source code 6 votes vote down vote up
private void logInfo(String msg) {
    if (logPath == null) {
        logger.info(msg);
    } else {
        try {
            FileUtils.createFile(logPath);
            // WTF windows
            FileWriter fw = new FileWriter(logPath, true);
            fw.write(msg);
            fw.write("\n");
            fw.flush();
            fw.close();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }
}
 
Example 15
Project: Quavo   File: UnderlayTypeList.java   View source code 6 votes vote down vote up
@Override
public void print() {
	File dir = new File(Constants.TYPE_PATH);

	if (!dir.exists()) {
		dir.mkdir();
	}

	File file = new File(Constants.TYPE_PATH, "underlays.txt");
	try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
		Arrays.stream(lays).filter(Objects::nonNull).forEach((UnderlayType t) -> {
			TypePrinter.print(t, writer);
		});
		writer.flush();
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 16
Project: tianti   File: GenCodeUtil.java   View source code 6 votes vote down vote up
/**
 * 创建Dao接口
 * @param c实体类
 * @param commonPackage 基础包:如com.jeff.tianti.info
 * @param author 作者
 * @param desc 描述
 * @throws IOException
 */
public static void createDaoInterface(Class c,String commonPackage,String author) throws IOException{
	String cName = c.getName();
	String daoPath = "";
	if(author == null || author.equals("")){
		author = "Administrator";
	}
	if(commonPackage != null && !commonPackage.equals("")){
		daoPath = commonPackage.replace(".", "/");
		String fileName = System.getProperty("user.dir") + "/src/main/java/" + daoPath+"/dao"
				+ "/" + getLastChar(cName) + "Dao.java";
		File f = new File(fileName);
		FileWriter fw = new FileWriter(f);
		fw.write("package "+commonPackage+".dao"+";"+RT_2+"import "+commonPackage+".entity"+"."+getLastChar(cName)+";"+RT_1+"import com.jeff.tianti.common.dao.CommonDao;"+RT_2
				+"/**"+RT_1+BLANK_1+"*"+BLANK_1+ANNOTATION_AUTHOR_PARAMTER+ author +RT_1
				+BLANK_1+"*"+BLANK_1+ANNOTATION_DESC +getLastChar(cName)+"Dao接口"+BLANK_1+RT_1
				+BLANK_1+"*"+BLANK_1+ANNOTATION_DATE +getDate()+RT_1+BLANK_1+"*/"+RT_1
				+"public interface " +getLastChar(cName) +"Dao extends "+getLastChar(cName)+"DaoCustom,CommonDao<"+getLastChar(cName)+",String>{"+RT_2+"}");
		fw.flush();
		fw.close();
		showInfo(fileName);
	}else{
		System.out.println("创建Dao接口失败,原因是commonPackage为空!");
	}
}
 
Example 17
Project: incubator-netbeans   File: AnnotationProcessorTestUtils.java   View source code 6 votes vote down vote up
/**
 * Create a source file.
 * @param dir source root
 * @param clazz a fully-qualified class name
 * @param content lines of text (skip package decl)
 */
public static void makeSource(File dir, String clazz, String... content) throws IOException {
    File f = new File(dir, clazz.replace('.', File.separatorChar) + ".java");
    f.getParentFile().mkdirs();
    Writer w = new FileWriter(f);
    try {
        PrintWriter pw = new PrintWriter(w);
        String pkg = clazz.replaceFirst("\\.[^.]+$", "");
        if (!pkg.equals(clazz) && !clazz.endsWith(".package-info")) {
            pw.println("package " + pkg + ";");
        }
        for (String line : content) {
            pw.println(line);
        }
        pw.flush();
    } finally {
        w.close();
    }
}
 
Example 18
Project: CSE112   File: Proc.java   View source code 6 votes vote down vote up
public void simulate() throws IOException {
	
	while(k==1 || !currnt.Field2.equals("ef000011")){//updt termination condition
	fetch();
	decode();
	execute();
	memory();
	write();
	System.out.println("***************************************************");
	}
	
	 FileWriter fw=new FileWriter("Maa_ki_chu.txt");/////////////////////
	 
	 for(int i=0;i<use_to_store.size()-1;i=i+2)
	 {
	
        fw.write(use_to_store.get(i)+" "+ use_to_store.get(i+1));    
	 }
        fw.close(); 
	
}
 
Example 19
Project: kafka-connect-fs   File: TextFileReaderTest.java   View source code 6 votes vote down vote up
private static Path createDataFile() throws IOException {
    File txtFile = File.createTempFile("test-", "." + FILE_EXTENSION);
    try (FileWriter writer = new FileWriter(txtFile)) {

        IntStream.range(0, NUM_RECORDS).forEach(index -> {
            String value = String.format("%d_%s", index, UUID.randomUUID());
            try {
                writer.append(value + "\n");
                OFFSETS_BY_INDEX.put(index, Long.valueOf(index++));
            } catch (IOException ioe) {
                throw new RuntimeException(ioe);
            }
        });
    }
    Path path = new Path(new Path(fsUri), txtFile.getName());
    fs.moveFromLocalFile(new Path(txtFile.getAbsolutePath()), path);
    return path;
}
 
Example 20
Project: Enjin-Coin-Java-SDK   File: JsonConfigTest.java   View source code 6 votes vote down vote up
@Test
public void testUpdate_SuccessOldAndNewHaveSameKeys() throws Exception {
    Object data = new Object();
    File mockFile = PowerMockito.mock(File.class);
    JsonObject oldJsonObject = new JsonObject();
    oldJsonObject.addProperty("id", "1");

    FileWriter mockFileWriter = PowerMockito.mock(FileWriter.class);
    FileWriter spyFileWriter = Mockito.spy(mockFileWriter);

    PowerMockito.mockStatic(JsonUtils.class);
    PowerMockito.when(JsonUtils.convertObjectToJsonTree(Mockito.isA(Gson.class), Mockito.any())).thenReturn(oldJsonObject, oldJsonObject);
    PowerMockito.whenNew(FileWriter.class).withParameterTypes(File.class).withArguments(mockFile).thenReturn(mockFileWriter);
    PowerMockito.when(JsonUtils.convertObjectToJson(Mockito.isA(Gson.class), Mockito.any())).thenReturn("{}");
    Mockito.doNothing().when(spyFileWriter).write(Mockito.anyString());
    Mockito.doNothing().when(spyFileWriter).close();

    JsonConfig jsonConfig = new JsonConfig();
    boolean result = jsonConfig.update(mockFile, data);
    assertThat(result).isTrue();

    PowerMockito.verifyNew(FileWriter.class, Mockito.times(1)).withArguments(Mockito.isA(File.class));
}
 
Example 21
Project: OpenDA   File: SwanStochObserverRegexTest.java   View source code 6 votes vote down vote up
private void retrieveAndWriteValues(IStochObserver stochObserver, OutputType outputType, String outputFileName, int ensembleCount, File stochObsWorkingDir) throws IOException {
    Locale locale = new Locale("EN");
    BufferedWriter realizationsFile = new BufferedWriter(new FileWriter(new File(stochObsWorkingDir, outputFileName)));

    realizationsFile.write("Ensemble members 1 to " + ensembleCount);
    realizationsFile.newLine();
    for (int iEnsemble = 1; iEnsemble <= ensembleCount; iEnsemble++) {
        double[] retrievedValues;
        if (outputType == OutputType.Values) {
            retrievedValues = stochObserver.getValues().getValues();
        } else if (outputType == OutputType.Realizations) {
            retrievedValues = stochObserver.getRealizations().getValues();
        } else if (outputType == OutputType.StandardDeviations) {
            retrievedValues = stochObserver.getStandardDeviations().getValues();
        } else {
            throw new RuntimeException("Unexpected output type");
        }
        assertEquals("#retrievedValues", 55, retrievedValues.length);
        realizationsFile.write(String.format(locale, "%16.5f", retrievedValues[0]));
        for (int i = 1; i < retrievedValues.length; i++) {
            realizationsFile.write(String.format(locale, ", %16.5f", retrievedValues[i]));
        }
        realizationsFile.newLine();
    }
    realizationsFile.close();
}
 
Example 22
Project: Quavo   File: VarClientTypeList.java   View source code 6 votes vote down vote up
@Override
public void print() {

	File dir = new File(Constants.TYPE_PATH);

	if (!dir.exists()) {
		dir.mkdir();
	}

	File file = new File(Constants.TYPE_PATH, "varclients.txt");
	try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
		Arrays.stream(varClients).filter(Objects::nonNull).forEach((VarClientType t) -> {
			TypePrinter.print(t, writer);
		});
		writer.flush();
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 23
Project: candlelight   File: Ludwig.java   View source code 6 votes vote down vote up
private void saveDungeon(Stage stage)
{
	FileChooser chooser = new FileChooser();
	chooser.setInitialFileName("dungeon.json");
	File file = chooser.showSaveDialog(stage);

	if (file != null)
	{
		try
		{
			BufferedWriter writer = new BufferedWriter(new FileWriter(file));
			JSONObject data = Dungeon.writeToJSON(this.dungeon);
			JSON.write(writer, data);
			writer.flush();
			writer.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
}
 
Example 24
Project: Learning-Spring-Boot-2.0-Second-Edition   File: ImageService.java   View source code 6 votes vote down vote up
/**
 * Pre-load some test images
 *
 * @return Spring Boot {@link CommandLineRunner} automatically
 *         run after app context is loaded.
 */
@Bean
CommandLineRunner setUp() throws IOException {
	return (args) -> {
		FileSystemUtils.deleteRecursively(new File(UPLOAD_ROOT));

		Files.createDirectory(Paths.get(UPLOAD_ROOT));

		FileCopyUtils.copy("Test file",
			new FileWriter(UPLOAD_ROOT +
				"/learning-spring-boot-cover.jpg"));

		FileCopyUtils.copy("Test file2",
			new FileWriter(UPLOAD_ROOT +
				"/learning-spring-boot-2nd-edition-cover.jpg"));

		FileCopyUtils.copy("Test file3",
			new FileWriter(UPLOAD_ROOT + "/bazinga.png"));
	};
}
 
Example 25
Project: Learning-Spring-Boot-2.0-Second-Edition   File: ImageService.java   View source code 6 votes vote down vote up
/**
 * Pre-load some fake images
 *
 * @return Spring Boot {@link CommandLineRunner} automatically run after app context is loaded.
 */
@Bean
CommandLineRunner setUp() throws IOException {
	return (args) -> {
		FileSystemUtils.deleteRecursively(new File(UPLOAD_ROOT));

		Files.createDirectory(Paths.get(UPLOAD_ROOT));

		FileCopyUtils.copy("Test file",
			new FileWriter(UPLOAD_ROOT +
				"/learning-spring-boot-cover.jpg"));

		FileCopyUtils.copy("Test file2",
			new FileWriter(UPLOAD_ROOT +
				"/learning-spring-boot-2nd-edition-cover.jpg"));

		FileCopyUtils.copy("Test file3",
			new FileWriter(UPLOAD_ROOT + "/bazinga.png"));
	};
}
 
Example 26
Project: TeamNote   File: DownloadServiceImpl.java   View source code 6 votes vote down vote up
public File downloadNote(int noteId, String type, String leftPath)throws IOException, DocumentException {
    Note note = noteDao.getNoteById(noteId);
    String currentVersion = note.getHistory().get(note.getVersionPointer());
    JsonObject obj = new JsonParser().parse(currentVersion).getAsJsonObject();
    String content = obj.get("content").getAsString();
    String htmlPath = leftPath + "htmlTemp.html";
    File file = new File(htmlPath);
    file.createNewFile();
    FileWriter writer = new FileWriter(file);
    writer.write("<body>" + content + "</body>");
    writer.close();
    if(type.equals("pdf")) {
        String pdfPath = leftPath + "pdfTemp.pdf";
        File pdfFile = new File(pdfPath);
        exportUtil.htmlToPdf(htmlPath, pdfFile);
        file.delete();
        file = pdfFile;
    }
    //default html
    return file;

}
 
Example 27
Project: featurea   File: SummaryDialog.java   View source code 6 votes vote down vote up
private void btnSaveAsActionPerformed(ActionEvent paramActionEvent) {
    JFileChooser localJFileChooser = new JFileChooser();
    localJFileChooser.addChoosableFileFilter(new JavaFileFilter("html", "HTML Files"));
    localJFileChooser.addChoosableFileFilter(new JavaFileFilter("doc", "Document Files"));
    localJFileChooser.addChoosableFileFilter(new JavaFileFilter("txt", "Text Files"));
    int i = localJFileChooser.showSaveDialog(this);
    if (i != 0) {
        return;
    }
    String str = localJFileChooser.getSelectedFile().getAbsolutePath();
    try {
        FileWriter localFileWriter = new FileWriter(str, false);
        localFileWriter.write(this.txtSumary.getText());
        localFileWriter.close();
    } catch (FileNotFoundException localFileNotFoundException) {
        localFileNotFoundException.printStackTrace();
        return;
    } catch (IOException localIOException) {
        localIOException.printStackTrace();
        return;
    }
}
 
Example 28
Project: StackNet   File: PythonGenericRegressor.java   View source code 6 votes vote down vote up
/**
* 
* @param filename : the conifiguration file name for required to run xgboost from the command line
* @param datset : the dataset to be used
* @param model : model dump name
* @param columns : Number of columns in the data
*/
 private void create_config_file(String filename , String datset, String model, int columns){

try{  // Catch errors in I/O if necessary.
	  // Open a file to write to.
	
		String saveFile = filename;
		
		FileWriter writer = new FileWriter(saveFile);
		writer.append("task=train\n");
	    writer.append("columns=" + columns+ "\n");					
	    writer.append("model=" +model+ "\n");	
	    writer.append("data=" +datset+ "\n");				    
	    writer.append("n_jobs=" + this.threads + "\n");
	    writer.append("random_state=" +  this.seed + "\n");
	    if (this.verbose){
	    	writer.append("verbose=1" +  "\n");
	    }else {
	    	writer.append("verbose=0" +  "\n");			    	
	    }		    
		writer.close();

   	} catch (Exception e) {
   		throw new IllegalStateException(" failed to write the config file at: " + filename);
   	}    
 }
 
Example 29
Project: s-store   File: TableStatsPrinter.java   View source code 6 votes vote down vote up
@Override
public String formatFinalResults(BenchmarkResults br) {
    if (this.stop) return (null);
    
    VoltTable vt = new VoltTable(COLUMNS);
    for (Object row[] : this.results) {
        vt.addRow(row);
    }
    
    try {
        FileWriter writer = new FileWriter(this.outputPath);
        VoltTableUtil.csv(writer, vt, true);
        writer.close();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
    LOG.info("Wrote CSV table stats periodically to '" + this.outputPath.getAbsolutePath() + "'");
    return (null);
}
 
Example 30
Project: browser   File: BookmarkManager.java   View source code 6 votes vote down vote up
/**
 * This method adds the the HistoryItem item to permanent bookmark storage
 * 
 * @param item
 */
private synchronized boolean addBookmark(HistoryItem item) {
	File bookmarksFile = new File(mContext.getFilesDir(), FILE_BOOKMARKS);
	if (item.getUrl() == null || mBookmarkMap.containsKey(item.getUrl())) {
		return false;
	}
	try {
		BufferedWriter bookmarkWriter = new BufferedWriter(new FileWriter(bookmarksFile, true));
		JSONObject object = new JSONObject();
		object.put(TITLE, item.getTitle());
		object.put(URL, item.getUrl());
		object.put(FOLDER, item.getFolder());
		object.put(ORDER, item.getOrder());

		bookmarkWriter.write(object.toString());
		bookmarkWriter.newLine();
		bookmarkWriter.close();
		mBookmarkMap.put(item.getUrl(), 1);
	} catch (IOException | JSONException e) {
		e.printStackTrace();
	}
	return true;
}
 
Example 31
Project: incubator-netbeans   File: TokenDumpCheck.java   View source code 6 votes vote down vote up
public void finish() throws Exception {
    if (input == null) {
        if (!outputFile.createNewFile()) {
            NbTestCase.fail("Cannot create file " + outputFile);
        }
        FileWriter fw = new FileWriter(outputFile);
        try {
            fw.write(output.toString());
        } finally {
            fw.close();
        }
        NbTestCase.fail("Created tokens dump file " + outputFile + "\nPlease re-run the test.");

    } else {
        if (inputIndex < input.length()) {
            NbTestCase.fail("Some text left unread:" + input.substring(inputIndex));
        }
    }
}
 
Example 32
Project: alfresco-repository   File: RenameUserTest.java   View source code 6 votes vote down vote up
private void createFile(String content) throws Exception
{
    file = File.createTempFile("RenameUserTest", ".txt");
    args[4] = "-file";
    args[5] = file.getPath();

    BufferedWriter out = new BufferedWriter(new FileWriter(file));
    out.write(content);
    out.close();
}
 
Example 33
Project: etomica   File: MeterVirialBDBin.java   View source code 6 votes vote down vote up
public void writeData(String filename) {
    try {
        FileWriter fw = new FileWriter(filename);
        fw.write(""+totalCount+"\n");
        for (int i=0; i<unscreenedCount.length; i++) {
            long sampleCount = accumulators[i].getSampleCount();
            if (sampleCount == 0) continue;
            long usc = unscreenedCount[i];
            AllData ad = accumulators[i].getRawData();
            fw.write(i+" "+usc+" "+ad.count+" "+((DataDoubleBDArray)ad.sum).getData()[0].toString()+" "+((DataDoubleBDArray)ad.sumSquare).getData()[0].toString()+"\n");
        }
        fw.close();
    }
    catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 34
Project: hadoop   File: TestConfiguration.java   View source code 6 votes vote down vote up
public void testFloatValues() throws IOException {
  out=new BufferedWriter(new FileWriter(CONFIG));
  startConfig();
  appendProperty("test.float1", "3.1415");
  appendProperty("test.float2", "003.1415");
  appendProperty("test.float3", "-3.1415");
  appendProperty("test.float4", " -3.1415 ");
  appendProperty("test.float5", "xyz-3.1415xyz");
  endConfig();
  Path fileResource = new Path(CONFIG);
  conf.addResource(fileResource);
  assertEquals(3.1415f, conf.getFloat("test.float1", 0.0f));
  assertEquals(3.1415f, conf.getFloat("test.float2", 0.0f));
  assertEquals(-3.1415f, conf.getFloat("test.float3", 0.0f));
  assertEquals(-3.1415f, conf.getFloat("test.float4", 0.0f));
  try {
    conf.getFloat("test.float5", 0.0f);
    fail("Property had invalid float value, but was read successfully.");
  } catch (NumberFormatException e) {
    // pass
  }
}
 
Example 35
Project: PACE   File: LocalSignatureKeyContainerTest.java   View source code 6 votes vote down vote up
@Test
public void writeReadTest() throws Exception {
  for (ValueSigner signer : ValueSigner.values()) {
    KeyPairGenerator gen = KeyPairGenerator.getInstance(signer.getKeyGenerationAlgorithm());
    if (signer == ValueSigner.ECDSA) {
      gen.initialize(256);
    } else {
      gen.initialize(1024);
    }

    KeyPair pair = gen.generateKeyPair();
    byte[] keyId = String.format("%s_%s", gen.getAlgorithm(), "test").getBytes(ENCODING_CHARSET);
    LocalSignatureKeyContainer container = new LocalSignatureKeyContainer(pair, keyId);

    File file = folder.newFile();
    FileWriter writer = new FileWriter(file);
    container.write(writer);
    writer.close();

    LocalSignatureKeyContainer container2 = LocalSignatureKeyContainer.read(new FileReader(file));
    assertThat("has matching keys", container2.getSigningKey().key.getEncoded(), equalTo(container.getSigningKey().key.getEncoded()));
    assertThat("has matching keys", container2.getSigningKey().id, equalTo(container.getSigningKey().id));
    assertThat("has matching keys", container2.getVerifyingKey(keyId).getEncoded(), equalTo(container.getVerifyingKey(keyId).getEncoded()));
  }

}
 
Example 36
Project: aliyun-maxcompute-data-collectors   File: OracleCallExportTest.java   View source code 6 votes vote down vote up
public void testExportUsingProcedure() throws IOException, SQLException {
  String[] lines = {
    "0,textfield0,2002-12-29 08:40:00,3300",
    "1,textfield1,2007-06-04 13:15:10,4400",
  };
  new File(getWarehouseDir()).mkdirs();
  File file = new File(getWarehouseDir() + "/part-00000");
  Writer output = new BufferedWriter(new FileWriter(file));
  for (String line : lines) {
    output.write(line);
    output.write("\n");
  }
  output.close();
  runExport(getArgv());
  verifyExport(2, getConnection());
}
 
Example 37
Project: n4js   File: NpmPackageToProjectAdapter.java   View source code 6 votes vote down vote up
/**
 * Writes contents of the {@link N4MFConstants#N4MF_MANIFEST manifest file} for a given npm package.
 *
 * @param projectFolder
 *            root folder of the npm package in which manifest is written
 * @param packageJSON
 *            that will be used as manifest data source
 * @param mainModule
 *            the main module
 * @param manifest
 *            file to which contents should be written
 *
 */
private void generateManifestContent(File projectFolder, PackageJson packageJSON, String mainModule,
		File manifest)
		throws IOException {

	String projectId = packageJSON.name;
	String projectVersion = packageJSON.version;

	if (!projectFolder.getName().equals(projectId)) {
		LOGGER.warn("project folder and project name are different : " + projectFolder.getName() + " <> + "
				+ packageJSON.name);
	}

	try (FileWriter fw = new FileWriter(manifest)) {
		fw.write(manifestContentProvider.getContent(projectId, ".", ".", mainModule, projectVersion));
	}
}
 
Example 38
Project: hadoop   File: TestConfiguration.java   View source code 6 votes vote down vote up
public void testPropertySource() throws IOException {
  out = new BufferedWriter(new FileWriter(CONFIG));
  startConfig();
  appendProperty("test.foo", "bar");
  endConfig();
  Path fileResource = new Path(CONFIG);
  conf.addResource(fileResource);
  conf.set("fs.defaultFS", "value");
  String [] sources = conf.getPropertySources("test.foo");
  assertEquals(1, sources.length);
  assertEquals(
      "Resource string returned for a file-loaded property" +
      " must be a proper absolute path",
      fileResource,
      new Path(sources[0]));
  assertArrayEquals("Resource string returned for a set() property must be " +
  		"\"programatically\"",
      new String[]{"programatically"},
      conf.getPropertySources("fs.defaultFS"));
  assertEquals("Resource string returned for an unset property must be null",
      null, conf.getPropertySources("fs.defaultFoo"));
}
 
Example 39
Project: lembredio   File: CadastroInterface.java   View source code 6 votes vote down vote up
public void swapFile(String file1) throws FileNotFoundException, IOException{
            File file = new File(file1);
            if(!file.exists()) file.createNewFile();
            FileWriter outputfile = new FileWriter(file1, true);
            PrintWriter out = new PrintWriter(outputfile);

                out.println(vlogin.type);
                out.println(vlogin.login);
                out.println(vlogin.senha);
                out.println(plogin.nome);
                out.println(plogin.email);
                if(vlogin.type==1) out.println(medico.getCRM());
                if(vlogin.type==2) out.println(farma.getnomeFarmacia());
                

          out.close();
}
 
Example 40
Project: Java-Data-Science-Cookbook   File: JsonWriting.java   View source code 6 votes vote down vote up
public void writeJson(String outFileName){
	JSONObject obj = new JSONObject();
	obj.put("book", "Harry Potter and the Philosopher's Stone");
	obj.put("author", "J. K. Rowling");

	JSONArray list = new JSONArray();
	list.add("There are characters in this book that will remind us of all the people we have met. Everybody knows or knew a spoilt, overweight boy like Dudley or a bossy and interfering (yet kind-hearted) girl like Hermione");
	list.add("Hogwarts is a truly magical place, not only in the most obvious way but also in all the detail that the author has gone to describe it so vibrantly.");
	list.add("Parents need to know that this thrill-a-minute story, the first in the Harry Potter series, respects kids' intelligence and motivates them to tackle its greater length and complexity, play imaginative games, and try to solve its logic puzzles. ");

	obj.put("messages", list);

	try {

		FileWriter file = new FileWriter(outFileName);
		file.write(obj.toJSONString());
		file.flush();
		file.close();

	} catch (IOException e) {
		e.printStackTrace();
	}

	System.out.print(obj);
}