Java 类java.io.FileWriter 实例源码

项目:NavyCraft2-Lite    文件:CraftMover.java   
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");
        }
    }
项目:ZooKeeper    文件:ZooInspectorManagerImpl.java   
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();
    }
}
项目:hadoop-oss    文件:TestConfiguration.java   
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]);
}
项目:MARF-for-Android    文件:SyntaxError.java   
/**
 * 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;
        }
    }
}
项目:integrations    文件:ConvertImages.java   
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();
}
项目:incubator-netbeans    文件:TopLoggingOwnConfigTest.java   
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();
}
项目:lembredio    文件:Farmaceutico.java   
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;
}
项目:cockroach    文件:NameStore.java   
@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();
}
项目:ATEBot    文件:Main.java   
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) {}
 }
项目:PekaED    文件:EpisodePanel.java   
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();
    }
}
项目:Soup    文件:HTMLGen.java   
/**
 * 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");
    }
}
项目:ibench    文件:HTMLPresenter.java   
/**
 * 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();
    }

}
项目:easy-test    文件:FindNotMakeTest.java   
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);
        }
    }
}
项目:Quavo    文件:UnderlayTypeList.java   
@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();
    }
}
项目:tianti    文件:GenCodeUtil.java   
/**
 * 创建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为空!");
    }
}
项目:incubator-netbeans    文件:AnnotationProcessorTestUtils.java   
/**
 * 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();
    }
}
项目:CSE112    文件:Proc.java   
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(); 

}
项目:kafka-connect-fs    文件:TextFileReaderTest.java   
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;
}
项目:Enjin-Coin-Java-SDK    文件:JsonConfigTest.java   
@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));
}
项目:OpenDA    文件:SwanStochObserverRegexTest.java   
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();
}
项目:Quavo    文件:VarClientTypeList.java   
@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();
    }
}
项目:candlelight    文件:Ludwig.java   
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();
        }
    }
}
项目:Learning-Spring-Boot-2.0-Second-Edition    文件:ImageService.java   
/**
 * 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"));
    };
}
项目:Learning-Spring-Boot-2.0-Second-Edition    文件:ImageService.java   
/**
 * 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"));
    };
}
项目:TeamNote    文件:DownloadServiceImpl.java   
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;

}
项目:featurea    文件:SummaryDialog.java   
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;
    }
}
项目:StackNet    文件:PythonGenericRegressor.java   
/**
* 
* @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);
    }    
 }
项目:s-store    文件:TableStatsPrinter.java   
@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);
}
项目:browser    文件:BookmarkManager.java   
/**
 * 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;
}
项目:incubator-netbeans    文件:TokenDumpCheck.java   
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));
        }
    }
}
项目:alfresco-repository    文件:RenameUserTest.java   
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();
}
项目:etomica    文件:MeterVirialBDBin.java   
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);
    }
}
项目:hadoop    文件:TestConfiguration.java   
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
  }
}
项目:PACE    文件:LocalSignatureKeyContainerTest.java   
@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()));
  }

}
项目:aliyun-maxcompute-data-collectors    文件:OracleCallExportTest.java   
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());
}
项目:n4js    文件:NpmPackageToProjectAdapter.java   
/**
 * 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));
    }
}
项目:hadoop    文件:TestConfiguration.java   
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"));
}
项目:lembredio    文件:CadastroInterface.java   
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();
}
项目:Java-Data-Science-Cookbook    文件:JsonWriting.java   
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);
}
项目:onprom    文件:UMLDiagramPanel.java   
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();
  }
}