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: ZooKeeper   File: ZooInspectorManagerImpl.java   Source Code and License 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 2
Project: NavyCraft2-Lite   File: CraftMover.java   Source Code and License 7 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 3
Project: NewKakaoBot   File: FileManager.java   Source Code and License 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: candlelight   File: Ludwig.java   Source Code and License 7 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 5
Project: hadoop-oss   File: TestConfiguration.java   Source Code and License 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 6
Project: MARF-for-Android   File: SyntaxError.java   Source Code and License 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 7
Project: integrations   File: ConvertImages.java   Source Code and License 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 8
Project: incubator-netbeans   File: TopLoggingOwnConfigTest.java   Source Code and License 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 9
Project: lembredio   File: Farmaceutico.java   Source Code and License 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 10
Project: cockroach   File: NameStore.java   Source Code and License 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 11
Project: ATEBot   File: Main.java   Source Code and License 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 12
Project: PekaED   File: EpisodePanel.java   Source Code and License 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 13
Project: Soup   File: HTMLGen.java   Source Code and License 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 14
Project: ibench   File: HTMLPresenter.java   Source Code and License 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 15
Project: easy-test   File: FindNotMakeTest.java   Source Code and License 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 16
Project: Quavo   File: UnderlayTypeList.java   Source Code and License 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 17
Project: tianti   File: GenCodeUtil.java   Source Code and License 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 18
Project: incubator-netbeans   File: AnnotationProcessorTestUtils.java   Source Code and License 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 19
Project: CSE112   File: Proc.java   Source Code and License 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 20
Project: kafka-connect-fs   File: TextFileReaderTest.java   Source Code and License 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 21
Project: Enjin-Coin-Java-SDK   File: JsonConfigTest.java   Source Code and License 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 22
Project: OpenDA   File: SwanStochObserverRegexTest.java   Source Code and License 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 23
Project: Quavo   File: VarClientTypeList.java   Source Code and License 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 24
Project: Learning-Spring-Boot-2.0-Second-Edition   File: ImageService.java   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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);
}
 
Example 41
Project: onprom   File: UMLDiagramPanel.java   Source Code and License 6 votes vote down vote up
public void exportImage() {
  try {
    File file = IOUtility.selectFileToSave(FileType.IMAGE);
    if (file != null) {
      Rectangle drawingArea = getDrawingArea();
      String extension = FilenameUtils.getExtension(file.getName());
      if (extension.equals("svg")) {
        SVGGraphics2D svgGenerator = IOUtility.getSVGGraphics(drawingArea.getSize());
        paintDrawing(svgGenerator, drawingArea.x, drawingArea.y);
        svgGenerator.stream(new FileWriter(file));
        svgGenerator.dispose();
      } else {
        BufferedImage bi = new BufferedImage(drawingArea.width, drawingArea.height, BufferedImage.TYPE_INT_RGB);
        Graphics g = bi.createGraphics();
        paintDrawing(g, drawingArea.x, drawingArea.y);
        ImageIO.write(bi, extension, file);
        g.dispose();
      }
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
}
 
Example 42
Project: openjdk-jdk10   File: TestIOException.java   Source Code and License 5 votes vote down vote up
@Test
void testReadOnlyFile() throws Exception {
    File outDir = new File("out2");
    if (!outDir.mkdir()) {
        throw new Error("Cannot create directory");
    }
    File index = new File(outDir, "index.html");
    try (FileWriter fw = new FileWriter(index)) { }
    if (!index.setReadOnly()) {
        throw new Error("could not set index read-only");
    }
    if (index.canWrite()) {
        throw new Error("index is writable");
    }

    try {
        setOutputDirectoryCheck(DirectoryCheck.NONE);
        javadoc("-d", outDir.toString(),
                new File(testSrc, "TestIOException.java").getPath());

        checkExit(Exit.ERROR);
        checkOutput(Output.OUT, true,
            "Error writing file: " + index);
    } finally {
        setOutputDirectoryCheck(DirectoryCheck.EMPTY);
        index.setWritable(true);
    }
}
 
Example 43
Project: iwant-demo   File: Iwant.java   Source Code and License 5 votes vote down vote up
public static void fileLog(String msg) {
	try (FileWriter fw = new FileWriter(new File(IWANT_USER_DIR, "log"),
			true)) {
		fw.append(new Date().toString()).append(" - ").append(msg)
				.append("\n");
	} catch (IOException e) {
		throw new IllegalStateException(e);
	}
}
 
Example 44
Project: bStats-Metrics   File: Metrics.java   Source Code and License 5 votes vote down vote up
/**
 * Writes a String to a file. It also adds a note for the user,
 *
 * @param file The file to write to. Cannot be null.
 * @param text The text to write.
 * @throws IOException If something did not work :(
 */
private void writeFile(File file, String text) throws IOException {
    if (!file.exists()) {
        file.createNewFile();
    }
    try (
            FileWriter fileWriter = new FileWriter(file);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)
    ) {
        bufferedWriter.write(text);
        bufferedWriter.newLine();
        bufferedWriter.write("Note: This class only exists for internal purpose. You can ignore it :)");
    }
}
 
Example 45
Project: monarch   File: LauncherLifecycleCommands.java   Source Code and License 5 votes vote down vote up
@Deprecated
protected File readIntoTempFile(final String classpathResourceLocation) throws IOException {
  String resourceName = classpathResourceLocation
      .substring(classpathResourceLocation.lastIndexOf(File.separator) + 1);
  File resourceFile = new File(System.getProperty("java.io.tmpdir"), resourceName);

  if (!resourceFile.exists() && resourceFile.createNewFile()) {
    BufferedReader resourceReader = new BufferedReader(new InputStreamReader(
        ClassLoader.getSystemClassLoader().getResourceAsStream(classpathResourceLocation)));

    BufferedWriter resourceFileWriter = new BufferedWriter(new FileWriter(resourceFile, false));

    try {
      for (String line = resourceReader.readLine(); line != null; line =
          resourceReader.readLine()) {
        resourceFileWriter.write(line);
        resourceFileWriter.write(StringUtils.LINE_SEPARATOR);
      }

      resourceFileWriter.flush();
    } finally {
      IOUtils.close(resourceReader);
      IOUtils.close(resourceFileWriter);
    }
  }

  resourceFile.deleteOnExit();

  return resourceFile;
}
 
Example 46
Project: ViperBot   File: Logger.java   Source Code and License 5 votes vote down vote up
public void logMessage(Chat chat, String sender, String msg){
	String chatName = chat.getIdentity();
	chatName = chatName.replaceFirst(chatName.split(":")[0] + ":","");		
	File f = new File(mainFolder, chatName + ".txt");
	try {
		BufferedWriter w = new BufferedWriter(new FileWriter(f, true));
		w.write(sender + " > " + msg + "\n");
		w.close();
		System.out.println(sender + " > " + msg);
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 47
Project: 3DSFE-Randomizer   File: FatesHub.java   Source Code and License 5 votes vote down vote up
private void createSettings() {
    File out = new File(System.getProperty("user.dir"), "settings.json");
    try (Writer writer = new FileWriter(out)) {
        GsonBuilder builder = new GsonBuilder();
        builder.setPrettyPrinting();
        Gson gson = builder.create();
        SettingsWrapper wrapper = new SettingsWrapper();
        wrapper.setGui(FatesGui.getInstance());
        wrapper.setCharacters(characters.getWorkingCharacters());
        gson.toJson(wrapper, writer);
    } catch(IOException ex) {
        ex.printStackTrace();
    }
}
 
Example 48
Project: intellij-deps-ini4j   File: ConfigParserTest.java   Source Code and License 5 votes vote down vote up
@Test public void testWrite() throws Exception
{
    File input = newTestFile(DWARFS_PATH);
    File output = new File(TEST_WORK_PATH, input.getName());

    instance.read(input);
    instance.write(output);
    checkWrite(output);
    instance.write(new FileWriter(output));
    checkWrite(output);
    instance.write(new FileOutputStream(output));
    checkWrite(output);
}
 
Example 49
Project: recipe-interpretation   File: RecipeSentenceSegmenter.java   Source Code and License 5 votes vote down vote up
public void createStepFiles(String dir) {
	File directory = new File(dir);
	File[] filelist = directory.listFiles();
	for (File file : filelist) {
		if (file.getName().endsWith(".txt")) {
			try {
				BufferedReader br = new BufferedReader(new FileReader(file));
				String line;
				List<String> steps = new ArrayList<String>();
				boolean in_steps = false;
				while ((line = br.readLine()) != null) {
					if (line.trim().length() == 0) {
						continue;
					} else if (line.trim().equals("Steps")) {
						in_steps = true;
					} else if (line.trim().equals("Ingredients")) {
						break;
					} else if (line.trim().startsWith("Data Parsed")) {
						break;
					} else if (in_steps) {
						steps.add(line.trim());
					}
				}
				br.close();

				BufferedWriter bw = new BufferedWriter(new FileWriter("/Users/chloe/Research/recipes/AllRecipesSteps/" + file.getName()));
				for (String step : steps) {
					List<String> sentences = Utils.splitStepSentences(step);
					for (String sentence : sentences) {
						bw.write(sentence + "\n");
					}
				}
				bw.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}
}
 
Example 50
Project: BaseClient   File: Shaders.java   Source Code and License 5 votes vote down vote up
public static void storeConfig()
{
    SMCLog.info("Save ShadersMod configuration.");

    if (shadersConfig == null)
    {
        shadersConfig = new PropertiesOrdered();
    }

    EnumShaderOption[] aenumshaderoption = EnumShaderOption.values();

    for (int i = 0; i < aenumshaderoption.length; ++i)
    {
        EnumShaderOption enumshaderoption = aenumshaderoption[i];
        String s = enumshaderoption.getPropertyKey();
        String s1 = getEnumShaderOption(enumshaderoption);
        shadersConfig.setProperty(s, s1);
    }

    try
    {
        FileWriter filewriter = new FileWriter(configFile);
        shadersConfig.store((Writer)filewriter, (String)null);
        filewriter.close();
    }
    catch (Exception exception)
    {
        SMCLog.severe("Error saving configuration: " + exception.getClass().getName() + ": " + exception.getMessage());
    }
}
 
Example 51
Project: diycode   File: CrashHandler.java   Source Code and License 5 votes vote down vote up
private void dumpExceptionToSDCard(Throwable ex) throws IOException {
    //如果SD卡不存在或无法使用,则无法把异常信息写入SD卡
    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        if (DEBUG) {
            Log.w(TAG, "sdcard unmounted,skip dump exception");
            return;
        }
    }

    File dir = new File(PATH);
    if (!dir.exists()) {
        dir.mkdirs();
    }
    long current = System.currentTimeMillis();
    String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(current));
    //以当前时间创建log文件
    File file = new File(PATH + FILE_NAME + time + FILE_NAME_SUFFIX);

    try {
        PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
        //导出发生异常的时间
        pw.println(time);

        //导出手机信息
        dumpPhoneInfo(pw);

        pw.println();
        //导出异常的调用栈信息
        ex.printStackTrace(pw);

        pw.close();
    } catch (Exception e) {
        Log.e(TAG, "dump crash info failed");
    }
}
 
Example 52
Project: ClassroomFlipkart   File: getMotherboardSN.java   Source Code and License 5 votes vote down vote up
public static String getMotherboardSN() {
    String result = "";
    try {
        File file = File.createTempFile("realhowto",".vbs");
        file.deleteOnExit();
        FileWriter fw = new FileWriter(file);

        String vbs =
                "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
                        + "Set colItems = objWMIService.ExecQuery _ \n"
                        + "   (\"Select * from Win32_BaseBoard\") \n"
                        + "For Each objItem in colItems \n"
                        + "    Wscript.Echo objItem.SerialNumber \n"
                        + "    exit for  ' do the first cpu only! \n"
                        + "Next \n";

        fw.write(vbs);
        fw.close();
        Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
        BufferedReader input =
                new BufferedReader
                        (new InputStreamReader(p.getInputStream()));
        String line;
        while ((line = input.readLine()) != null) {
            result += line;
        }
        input.close();
    }
    catch(Exception e){
        e.printStackTrace();
    }
    return result.trim();
}
 
Example 53
Project: athena   File: CopyrightHeaderTest.java   Source Code and License 5 votes vote down vote up
/**
 * This test case checks the received copyright header contents.
 *
 * @throws IOException when fails to do IO operations
 */
@Test
public void testGetCopyrightHeader() throws IOException {

    String path = "src/test/resources/CopyrightHeader.txt";

    File testRsc = new File(path);
    FileInputStream in = new FileInputStream(testRsc);

    File testFile = new File("target/TestHeader.txt");
    FileOutputStream out = new FileOutputStream(testFile);

    out.write(COPYRIGHTS_FIRST_LINE.getBytes());
    int c = 0;
    while ((c = in.read()) != -1) {
        out.write(c);
    }

    String licenseHeader = getCopyrightHeader();
    File test = new File("target/TestCopyrightHeader.txt");

    FileWriter writer = new FileWriter(test);
    writer.write(licenseHeader);
    writer.close();
    out.close();
    out.flush();
    in.close();

    assertThat(true, is(contentEquals(test, testFile)));
    test.delete();
    testFile.delete();
}
 
Example 54
Project: 19porn   File: DiskLruCache.java   Source Code and License 5 votes vote down vote up
/**
     * Opens the cache in {@code directory}, creating a cache if none exists
     * there.
     *
     * @param directory  a writable directory
     * @param appVersion
     * @param valueCount the number of values per cache entry. Must be positive.
     * @param maxSize    the maximum number of bytes this cache should use to store
     * @throws IOException if reading or writing the cache directory fails
     */
    public static DiskLruCache open(File directory, int appVersion, int valueCount, long maxSize)
            throws IOException {
        if (maxSize <= 0) {
            throw new IllegalArgumentException("maxSize <= 0");
        }
        if (valueCount <= 0) {
            throw new IllegalArgumentException("valueCount <= 0");
        }

        // prefer to pick up where we left off
        DiskLruCache cache = new DiskLruCache(directory, appVersion, valueCount, maxSize);
        if (cache.journalFile.exists()) {
            try {
                cache.readJournal();
                cache.processJournal();
                cache.journalWriter = new BufferedWriter(new FileWriter(cache.journalFile, true),
                        IO_BUFFER_SIZE);
                return cache;
            } catch (IOException journalIsCorrupt) {
//                System.logW("DiskLruCache " + directory + " is corrupt: "
//                        + journalIsCorrupt.getMessage() + ", removing");
                cache.delete();
            }
        }

        // create a new empty cache
        directory.mkdirs();
        cache = new DiskLruCache(directory, appVersion, valueCount, maxSize);
        cache.rebuildJournal();
        return cache;
    }
 
Example 55
Project: ditb   File: TestJarFinder.java   Source Code and License 5 votes vote down vote up
@Test
public void testExistingManifest() throws Exception {
  File dir = new File(System.getProperty("test.build.dir", "target/test-dir"),
                      TestJarFinder.class.getName() + "-testExistingManifest");
  delete(dir);
  dir.mkdirs();

  File metaInfDir = new File(dir, "META-INF");
  metaInfDir.mkdirs();
  File manifestFile = new File(metaInfDir, "MANIFEST.MF");
  Manifest manifest = new Manifest();
  OutputStream os = new FileOutputStream(manifestFile);
  manifest.write(os);
  os.close();

  File propsFile = new File(dir, "props.properties");
  Writer writer = new FileWriter(propsFile);
  new Properties().store(writer, "");
  writer.close();
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  JarOutputStream zos = new JarOutputStream(baos);
  JarFinder.jarDir(dir, "", zos);
  JarInputStream jis =
    new JarInputStream(new ByteArrayInputStream(baos.toByteArray()));
  Assert.assertNotNull(jis.getManifest());
  jis.close();
}
 
Example 56
Project: parabuild-ci   File: DatabaseManagerCommon.java   Source Code and License 5 votes vote down vote up
/**
 * Method declaration
 *
 *
 * @param file
 * @param text
 */
static void writeFile(String file, String text) {

    try {
        FileWriter write = new FileWriter(file);

        write.write(text.toCharArray());
        write.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 57
Project: fuck_zookeeper   File: InvalidSnapCountTest.java   Source Code and License 5 votes vote down vote up
public MainThread(int clientPort) throws IOException {
    super("Standalone server with clientPort:" + clientPort);
    File tmpDir = ClientBase.createTmpDir();
    confFile = new File(tmpDir, "zoo.cfg");

    FileWriter fwriter = new FileWriter(confFile);
    fwriter.write("tickTime=2000\n");
    fwriter.write("initLimit=10\n");
    fwriter.write("syncLimit=5\n");
    fwriter.write("snapCount=1\n");

    File dataDir = new File(tmpDir, "data");
    if (!dataDir.mkdir()) {
        throw new IOException("unable to mkdir " + dataDir);
    }
    
    // Convert windows path to UNIX to avoid problems with "\"
    String dir = dataDir.toString();
    String osname = java.lang.System.getProperty("os.name");
    if (osname.toLowerCase().contains("windows")) {
        dir = dir.replace('\\', '/');
    }
    fwriter.write("dataDir=" + dir + "\n");
    
    fwriter.write("clientPort=" + clientPort + "\n");
    fwriter.flush();
    fwriter.close();

    main = new TestMain();
}
 
Example 58
Project: Kineticraft   File: JsonData.java   Source Code and License 5 votes vote down vote up
/**
 * Save this Json Object to a file.
 * @param path
 */
public void toFile(String path) {
    File file = getFile(path);

    try {
        FileWriter writer = new FileWriter(file);
        writer.write(toPrettyJson());
        writer.close();
    } catch (Exception e) {
        e.printStackTrace();
        Core.warn("Failed to save '" + file.getName() + "'.");
    }
}
 
Example 59
Project: uavstack   File: Log4jTest.java   Source Code and License 5 votes vote down vote up
public void writeStackTrace() throws IOException, InterruptedException {
    // used in window
    // File expectOutput = new File("D:\\logFolder\\expectOutput.txt");
    // FileWriter writerExpect = new FileWriter(expectOutput,true);

    // used in linux
    File expectOutput = new File("/home/work/UAV/Log/expectOutput.txt");
    @SuppressWarnings("resource")
    FileWriter writerExpect = new FileWriter(expectOutput, true);

    Thread.sleep(10000);
    logger.error("IOexception", new IOException("1111111111 failed.."));
    System.out.println(" IOexception >>>>  111111111");
    writerExpect.write(
            "{\"stacktrace\":\"java.io.IOException: 1111111111 failed..\\tat com.creditease.monitorframework.fat.Log4jTest.writeStackTrace(Log4jTest.java:191)\\tat com.creditease.monitorframework.fat.Log4jTest.doGet(Log4jTest.java:48)\\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:624)\\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:731)\\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:307)\\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:212)\\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)\\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:245)\\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:212)\\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)\\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)\\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)\\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)\\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)\\tat org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)\\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)\\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:443)\\tat org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)\\tat org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)\\tat org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)\\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)\\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)\\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\\tat java.lang.Thread.run(Thread.java:745)\"}\r\n");
    writerExpect.flush();

    Thread.sleep(10000);
    logger.error("InterruptedException", new InterruptedException("222222222 faild.."));
    System.out.println("InterruptedException >>> 222222222");
    writerExpect.write(
            "{\"stacktrace\":\"java.lang.InterruptedException: 222222222 faild..\\tat com.creditease.monitorframework.fat.Log4jTest.writeStackTrace(Log4jTest.java:197)\\tat com.creditease.monitorframework.fat.Log4jTest.doGet(Log4jTest.java:48)\\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:624)\\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:731)\\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:307)\\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:212)\\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)\\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:245)\\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:212)\\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)\\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)\\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)\\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)\\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)\\tat org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)\\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)\\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:443)\\tat org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)\\tat org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)\\tat org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)\\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)\\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)\\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\\tat java.lang.Thread.run(Thread.java:745)\"}\r\n");
    writerExpect.flush();

    Thread.sleep(10000);
    logger.error("ClassNotFoundException", new ClassNotFoundException("33333333"));
    System.out.println("ClassNotFoundException >>> 33333333");
    writerExpect.write(
            "{\"stacktrace\":\"java.lang.ClassNotFoundException: 33333333\\tat com.creditease.monitorframework.fat.Log4jTest.writeStackTrace(Log4jTest.java:203)\\tat com.creditease.monitorframework.fat.Log4jTest.doGet(Log4jTest.java:48)\\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:624)\\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:731)\\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:307)\\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:212)\\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)\\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:245)\\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:212)\\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)\\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)\\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)\\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)\\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)\\tat org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)\\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)\\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:443)\\tat org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)\\tat org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)\\tat org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)\\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)\\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)\\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\\tat java.lang.Thread.run(Thread.java:745)\"}\r\n");
    writerExpect.flush();

    System.out.println("*********** the end of stack trace *********");

}
 
Example 60
Project: PeSanKita-android   File: XmlBackup.java   Source Code and License 5 votes vote down vote up
public Writer(String path, int count) throws IOException {
  bufferedWriter = new BufferedWriter(new FileWriter(path, false));

  bufferedWriter.write(XML_HEADER);
  bufferedWriter.newLine();
  bufferedWriter.write(CREATED_BY);
  bufferedWriter.newLine();
  bufferedWriter.write(String.format(OPEN_TAG_SMSES, count));
}