Java 类java.io.BufferedWriter 实例源码

项目:BookReader-master    文件:LogUtils.java   
/**
 * 打开日志文件并写入日志
 *
 * @return
 **/
private synchronized static void log2File(String mylogtype, String tag, String text) {
    Date nowtime = new Date();
    String date = FILE_SUFFIX.format(nowtime);
    String dateLogContent = LOG_FORMAT.format(nowtime) + ":" + mylogtype + ":" + tag + ":" + text; // 日志输出格式
    File destDir = new File(LOG_FILE_PATH);
    if (!destDir.exists()) {
        destDir.mkdirs();
    }
    File file = new File(LOG_FILE_PATH, LOG_FILE_NAME + date);
    try {
        FileWriter filerWriter = new FileWriter(file, true);
        BufferedWriter bufWriter = new BufferedWriter(filerWriter);
        bufWriter.write(dateLogContent);
        bufWriter.newLine();
        bufWriter.close();
        filerWriter.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
项目:FastReading    文件:FileReadingAndWriting.java   
@Override
public FileWriteResult write(@NonNull File file, @NonNull String text, @NonNull PercentSender percentSender) {
    try {
        if (!file.exists() || !file.canWrite()) {
            return FileWriteResult.FAILURE;
        }

        percentSender.refreshPercents(0, 0);

        BufferedWriter writer = new BufferedWriter(new FileWriter(file));
        writer.write(text);

        writer.close();


        percentSender.refreshPercents(0, 100);
    } catch (IOException e) {
        e.printStackTrace();

        return FileWriteResult.FAILURE;
    }

    return FileWriteResult.SUCCESS;
}
项目:pre-dem-android    文件:LogUtils.java   
/**
 * 打印信息
 *
 * @param message
 */
public static synchronized void writeLog(String message) {
    File f = getFile();
    if (f != null) {
        try {
            FileWriter fw = new FileWriter(f, true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.append("\n");
            bw.append(message);
            bw.append("\n");
            bw.flush();
            bw.close();
            fw.close();
        } catch (IOException e) {
            print("writeLog error, " + e.getMessage());
        }
    } else {
        print("writeLog error, due to the file dir is error");
    }
}
项目:powsybl-core    文件:CacheManager.java   
public Path create() {
    try {
        if (Files.exists(path)) {
            List<String> otherKeys;
            try (Stream<String> stream = Files.lines(getMetadataFile(), StandardCharsets.UTF_8)) {
                otherKeys = stream.collect(Collectors.toList());
            }
            if (!keys.equals(otherKeys)) {
                throw new PowsyblException("Inconsistent cache hash code");
            }
        } else {
            Files.createDirectories(path);
            try (BufferedWriter writer = Files.newBufferedWriter(getMetadataFile(), StandardCharsets.UTF_8)) {
                for (String key : keys) {
                    writer.write(key);
                    writer.newLine();
                }
            }
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
    return path;
}
项目:hadoop    文件:FSNamesystem.java   
/**
 * Dump all metadata into specified file
 */
void metaSave(String filename) throws IOException {
  checkSuperuserPrivilege();
  checkOperation(OperationCategory.UNCHECKED);
  writeLock();
  try {
    checkOperation(OperationCategory.UNCHECKED);
    File file = new File(System.getProperty("hadoop.log.dir"), filename);
    PrintWriter out = new PrintWriter(new BufferedWriter(
        new OutputStreamWriter(new FileOutputStream(file), Charsets.UTF_8)));
    metaSave(out);
    out.flush();
    out.close();
  } finally {
    writeUnlock();
  }
}
项目:hanlpStudy    文件:TMDictionaryMaker.java   
@Override
public boolean saveTxtTo(String path)
{
    try
    {
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(IOUtil.newOutputStream(path)));
        bw.write(toString());
        bw.close();
    }
    catch (Exception e)
    {
        logger.warning("在保存转移矩阵词典到" + path + "时发生异常" + e);
        return false;
    }
    return true;
}
项目:gate-core    文件:DocumentStaxUtils.java   
/**
 * Save the content of a document to the given output stream. Since
 * XCES content files are plain text (not XML), XML-illegal characters
 * are not replaced when writing. The stream is <i>not</i> closed by
 * this method, that is left to the caller.
 * 
 * @param doc the document to save
 * @param out the stream to write to
 * @param encoding the character encoding to use. If null, defaults to
 *          UTF-8
 */
public static void writeXcesContent(Document doc, OutputStream out,
        String encoding) throws IOException {
  if(encoding == null) {
    encoding = "UTF-8";
  }

  String documentContent = doc.getContent().toString();

  OutputStreamWriter osw = new OutputStreamWriter(out, encoding);
  BufferedWriter writer = new BufferedWriter(osw);
  writer.write(documentContent);
  writer.flush();
  // do not close the writer, this would close the underlying stream,
  // which is something we want to leave to the caller
}
项目:Coder    文件:DiskLruCache.java   
private void readJournal() throws IOException {
  StrictLineReader reader = new StrictLineReader(new FileInputStream(journalFile), DiskUtil.US_ASCII);
  try {
    String magic = reader.readLine();
    String version = reader.readLine();
    String appVersionString = reader.readLine();
    String valueCountString = reader.readLine();
    String blank = reader.readLine();
    if (!MAGIC.equals(magic)
        || !VERSION_1.equals(version)
        || !Integer.toString(appVersion).equals(appVersionString)
        || !Integer.toString(valueCount).equals(valueCountString)
        || !"".equals(blank)) {
      throw new IOException("unexpected journal header: [" + magic + ", " + version + ", "
          + valueCountString + ", " + blank + "]");
    }

    int lineCount = 0;
    while (true) {
      try {
        readJournalLine(reader.readLine());
        lineCount++;
      } catch (EOFException endOfJournal) {
        break;
      }
    }
    redundantOpCount = lineCount - lruEntries.size();

    // If we ended on a truncated line, rebuild the journal before appending to it.
    if (reader.hasUnterminatedLine()) {
      rebuildJournal();
    } else {
      journalWriter = new BufferedWriter(new OutputStreamWriter(
          new FileOutputStream(journalFile, true), DiskUtil.US_ASCII));
    }
  } finally {
    DiskUtil.closeQuietly(reader);
  }
}
项目:UaicNlpToolkit    文件:PrecompileFromDexOnlineDB.java   
public static void updateReflPronouns(Connection con) throws SQLException, IOException {
    MyDictionary dictionary = new MyDictionary();
    Statement stmt = con.createStatement();
    long k = 0;
    ResultSet rs = stmt.executeQuery("SELECT \n"
            + "             inflectedform.formUtf8General as inflForm, \n"
            + "             inflectedform.inflectionId as inflId, \n"
            + "     lexem.formUtf8General as lemma,\n"
            + "             definition.internalRep as definition\n"
            + "FROM inflectedform \n"
            + "JOIN lexemmodel on inflectedform.lexemmodelId=lexemmodel.id \n"
            + "JOIN lexem on lexemmodel.lexemId=lexem.id \n"
            + "JOIN lexemdefinitionmap on lexemdefinitionmap.lexemId=lexem.Id \n"
            + "JOIN definition on definition.id = lexemdefinitionmap.definitionId \n"
            + "WHERE (inflectedform.inflectionId=84 || (inflectedform.inflectionId>40 && inflectedform.inflectionId<49)) AND definition.internalRep LIKE '% #pron\\. refl\\.%' \n"
            + "ORDER BY inflectedform.formUtf8General");

    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(MyDictionary.folder + "grabedForUse/" + pronReflFile), "UTF8"));
    while (rs.next()) {
        MyDictionaryEntry entry = new MyDictionaryEntry(rs.getString("inflForm"), null, null, null);
        entry.setLemma(rs.getString("lemma"));
        entry.setMsd("Px");
        preprocessEntry(entry, rs.getInt("inflId"));

        if (!dictionary.contains(entry)) {
            out.write(entry.toString() + "\n");
            dictionary.Add(entry);
            k++;
        }
    }
    stmt.close();
    rs.close();
    out.close();
    System.out.println("Finished reflexive pronouns (" + k + " added)");
}
项目:pac4j-plus    文件:CasRestAuthenticator.java   
private String requestTicketGrantingTicket(final String username, final String password) {
    HttpURLConnection connection = null;
    try {
        connection = HttpUtils.openPostConnection(new URL(this.casRestUrl));
        final String payload = HttpUtils.encodeQueryParam(Pac4jConstants.USERNAME, username)
                + "&" + HttpUtils.encodeQueryParam(Pac4jConstants.PASSWORD, password);

        final BufferedWriter out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), HttpConstants.UTF8_ENCODING));
        out.write(payload);
        out.close();

        final String locationHeader = connection.getHeaderField("location");
        final int responseCode = connection.getResponseCode();
        if (locationHeader != null && responseCode == HttpConstants.CREATED) {
            return locationHeader.substring(locationHeader.lastIndexOf("/") + 1);
        }

        throw new TechnicalException("Ticket granting ticket request failed: " + locationHeader + " " + responseCode +
                HttpUtils.buildHttpErrorMessage(connection));
    } catch (final IOException e) {
        throw new TechnicalException(e);
    } finally {
        HttpUtils.closeConnection(connection);
    }
}
项目:OpenVSP3Plugin    文件:OpenVSP3Plugin.java   
void writeCompGeomScriptFile(String filename) throws Exception {
    LOG.trace("writeCompGeomScriptFile()");
    BufferedWriter bw = new BufferedWriter(new FileWriter(tempDir + "\\" + filename));
    bw.write("void main()"); bw.newLine();
    bw.write("{"); bw.newLine();
    bw.write("  SetComputationFileName(COMP_GEOM_TXT_TYPE, \"./OpenVSP3PluginCompGeom.txt\");"); bw.newLine();
    bw.write("  SetComputationFileName(COMP_GEOM_CSV_TYPE, \"./OpenVSP3PluginCompGeom.csv\");"); bw.newLine();
    bw.write("  ComputeCompGeom(0, false, COMP_GEOM_CSV_TYPE);"); bw.newLine();
    bw.write("  while ( GetNumTotalErrors() > 0 )"); bw.newLine();
    bw.write("  {"); bw.newLine();
    bw.write("    ErrorObj err = PopLastError();"); bw.newLine();
    bw.write("    Print( err.GetErrorString() );"); bw.newLine();
    bw.write("  }"); bw.newLine();
    bw.write("}"); bw.newLine();
    bw.close();
}
项目:Reer    文件:JavadocOptionFileWriter.java   
void write(File outputFile) throws IOException {
    IoActions.writeTextFile(outputFile, new ErroringAction<BufferedWriter>() {
        @Override
        protected void doExecute(BufferedWriter writer) throws Exception {
            final Map<String, JavadocOptionFileOption<?>> options = new TreeMap<String, JavadocOptionFileOption<?>>(optionFile.getOptions());
            JavadocOptionFileWriterContext writerContext = new JavadocOptionFileWriterContext(writer);

            JavadocOptionFileOption<?> localeOption = options.remove("locale");
            if (localeOption != null) {
                localeOption.write(writerContext);
            }

            for (final String option : options.keySet()) {
                options.get(option).write(writerContext);
            }

            optionFile.getSourceNames().write(writerContext);
        }
    });
}
项目:Military-North-Compass    文件:Compass.java   
private void save() {
    File file = new File(Environment.getExternalStorageDirectory()+"/save-compass-1.txt");
    try {
        FileWriter f = new FileWriter(file);
        BufferedWriter bufferedWriter = new BufferedWriter(f);
        bufferedWriter.write(
                O1X+"\n"+
                O1Y+"\n"+
                O1A+"\n"+
                O2X+"\n"+
                O2Y+"\n"+
                O2A+"\n"
        );
        bufferedWriter.flush();
        bufferedWriter.close();
        f.close();
    } catch (IOException e) {
        warn("無法儲存資料到 save-compass-1.txt", 0);
    }
}
项目:permission-map    文件:OutputGraph.java   
/**
 * Generate file representing the graph as comma separated edges.
 * @param outputName
 * @throws IOException 
 */
public void generateCSV(String outputName) throws IOException {
  // create directory to write graphs
  File graphDir = new File(Options.v().output_dir() +"/"+ "graphs/");
  if (!graphDir.exists())
    graphDir.mkdir();
  for (int i=0; i < ConfigCHA.v().getGraphOutMaxDepth(); i++) {
    String name =  graphDir.getAbsolutePath() +"/"+ i + outputName;
    out.add(new PrintWriter(new BufferedWriter(new FileWriter(name))));
    log.info("Output CSV graph to '"+ name);
  }
  Set<SootMethod> alreadyVisited = new HashSet<SootMethod>();
  SootMethod main = Scene.v().getMainMethod();
  alreadyVisited.add(main);
  visit(alreadyVisited, main, 0);

  for (int i=0; i < ConfigCHA.v().getGraphOutMaxDepth(); i++)
    out.get(i).close();

}
项目:ditb    文件:ResultParser2.java   
private void outputNetTraffic(Map<IndexType, RunStatistics> runStatMap) throws IOException {
  BufferedWriter bw = new BufferedWriter(new FileWriter(netTrafficFile));
  System.out.println("type\tInsert\tQuery");
  bw.write("type\tInsert\tQuery\n");
  RunStatistics base = runStatMap.get(IndexType.NoIndex);
  for (IndexType indexType : indexTypes) {
    RunStatistics stat = runStatMap.get(indexType);
    StringBuilder sb = new StringBuilder();
    sb.append(indexType).append("\t")
        .append(convert(stat.insertNetTraffic / base.insertNetTraffic)).append("\t")
        .append(convert(stat.scanNetTraffic / base.scanNetTraffic));
    System.out.println(sb.toString());
    bw.write(sb.toString() + "\n");
  }
  bw.close();
}
项目:JATS2LaTeX    文件:BodyStandard.java   
public static void body(BufferedWriter wrlatex, List<Section> listSections, String referenceLink) throws IOException {
    for (int j = 0; j < listSections.size(); j++) {
        Section section = listSections.get(j);
        sectionWriting(wrlatex, section);
    } //end of Sections
    wrlatex.newLine();
    wrlatex.write("\\bibliography{");
    wrlatex.write(referenceLink);
    wrlatex.write("}");
    wrlatex.newLine();
    wrlatex.write("\\end{document}");
    wrlatex.close();

}
项目:tablasco    文件:ExceptionHtml.java   
private static void writeDocument(Document document, File resultsFile) throws TransformerException, IOException
{
    File parentDir = resultsFile.getParentFile();
    if (!parentDir.exists() && !parentDir.mkdirs())
    {
        throw new IllegalStateException("Unable to create results directory:" + parentDir);
    }
    Transformer trans = TransformerFactory.newInstance().newTransformer();
    trans.setOutputProperty(OutputKeys.METHOD, "xml");
    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    trans.setOutputProperty(OutputKeys.INDENT, "yes");
    try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(resultsFile), "UTF-8")))
    {
        trans.transform(new DOMSource(document), new StreamResult(writer));
    }
}
项目:ArtOfAndroid    文件:TCPServerService.java   
private void responseClient(Socket client) throws IOException {
    //用于接收客户端消息
    BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    //用于向客户端发送消息
    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);
    out.println("欢迎来到聊天室!");
    while (!mIsServiceDestroyed) {
        String str = in.readLine();
        System.out.println("msg from client: " + str);
        if (str == null) {
            break;
        }
        int i = new Random().nextInt(mDefinedMessages.length);
        String msg = mDefinedMessages[i];
        out.println(msg);
        System.out.println("send: " + msg);
    }
    System.out.println("client quit.");
    //关闭流
    MyUtil.close(out);
    MyUtil.close(in);
    client.close();
}
项目:SaveableSerializing    文件:SaveableDataWriter.java   
public void flush(){
    try{
        if(targetFile.exists())
            targetFile.delete();
        targetFile.getParentFile().mkdirs();
        targetFile.createNewFile();

        BufferedWriter writer = new BufferedWriter(new FileWriter(targetFile));
        StringBuilder builder = new StringBuilder();
        for(SaveableData dat : toWrite)
        {
            writer.append("start subset ").append(dat.getName()).append("\n");
            dat.writeBy(builder);
            writer.append(builder);
            writer.append("end subset\n");
            builder = new StringBuilder();
        }

        writer.flush();
        writer.close();
        toWrite.clear();
        }catch (Exception ex){}
}
项目:lodrecsys_eswc2017tutorial    文件:Convert2mymedialite.java   
/**
 * 
 * Convert from M1M format to mymedialite format
 * 
 * First argument: M1M file
 * Second argument: Output file
 * 
 */
public static void main(String[] args) {
    if (args.length == 2) {
        try {
            RatingsReader rr = new RatingsReader(new File(args[0]));
            BufferedWriter writer = new BufferedWriter(new FileWriter(args[1]));
            while (rr.hasNext()) {
                Rate r = rr.next();
                writer.append(String.valueOf(r.getUser())).append("\t").append(String.valueOf(r.getItem())).append("\t").append(String.valueOf(r.getRate()));
                writer.newLine();
            }
            writer.close();
        } catch (IOException ioex) {
            Logger.getLogger(Convert2mymedialite.class.getName()).log(Level.SEVERE, null, ioex);
        }
    }
}
项目:hadoop    文件:TestConfiguration.java   
public void testBooleanValues() throws IOException {
  out=new BufferedWriter(new FileWriter(CONFIG));
  startConfig();
  appendProperty("test.bool1", "true");
  appendProperty("test.bool2", "false");
  appendProperty("test.bool3", "  true ");
  appendProperty("test.bool4", " false ");
  appendProperty("test.bool5", "foo");
  appendProperty("test.bool6", "TRUE");
  appendProperty("test.bool7", "FALSE");
  appendProperty("test.bool8", "");
  endConfig();
  Path fileResource = new Path(CONFIG);
  conf.addResource(fileResource);
  assertEquals(true, conf.getBoolean("test.bool1", false));
  assertEquals(false, conf.getBoolean("test.bool2", true));
  assertEquals(true, conf.getBoolean("test.bool3", false));
  assertEquals(false, conf.getBoolean("test.bool4", true));
  assertEquals(true, conf.getBoolean("test.bool5", true));
  assertEquals(true, conf.getBoolean("test.bool6", false));
  assertEquals(false, conf.getBoolean("test.bool7", true));
  assertEquals(false, conf.getBoolean("test.bool8", false));
}
项目:JavaPlot    文件:FileUtils.java   
public static String createTempFile(String contents) throws IOException {
    File file = File.createTempFile("gnuplot_", ".dat");
    BufferedWriter out = new BufferedWriter(new FileWriter(file));
    out.append(contents);
    out.close();
    return file.getAbsolutePath();
}
项目:LoRaWAN-Smart-Parking    文件:HttpResponseCache.java   
public void writeTo(DiskLruCache.Editor editor) throws IOException {
  OutputStream out = editor.newOutputStream(ENTRY_METADATA);
  Writer writer = new BufferedWriter(new OutputStreamWriter(out, UTF_8));

  writer.write(uri + '\n');
  writer.write(requestMethod + '\n');
  writer.write(Integer.toString(varyHeaders.length()) + '\n');
  for (int i = 0; i < varyHeaders.length(); i++) {
    writer.write(varyHeaders.getFieldName(i) + ": " + varyHeaders.getValue(i) + '\n');
  }

  writer.write(responseHeaders.getStatusLine() + '\n');
  writer.write(Integer.toString(responseHeaders.length()) + '\n');
  for (int i = 0; i < responseHeaders.length(); i++) {
    writer.write(responseHeaders.getFieldName(i) + ": " + responseHeaders.getValue(i) + '\n');
  }

  if (isHttps()) {
    writer.write('\n');
    writer.write(cipherSuite + '\n');
    writeCertArray(writer, peerCertificates);
    writeCertArray(writer, localCertificates);
  }
  writer.close();
}
项目:winter    文件:Graph.java   
public void writePajekFormat(File f) throws IOException {
    BufferedWriter w = new BufferedWriter(new FileWriter(f));

    w.write(String.format("*Vertices %d\n", nodes.size()));
    for(Node<TNode> n : Q.sort(nodes.values(), new Node.NodeIdComparator<TNode>())) {
        w.write(String.format("%d \"%s\"\n", n.getId(), n.getData().toString()));
    }

    w.write(String.format("*Edges %d\n", edges.size()));
    for(Edge<TNode, TEdge> e : Q.sort(edges, new Edge.EdgeByNodeIdComparator<TNode, TEdge>())) {
        List<Node<TNode>> ordered = Q.sort(e.getNodes(), new Node.NodeIdComparator<TNode>());
        if(ordered.size()>1) {
            Node<TNode> n1 = ordered.get(0);
            Node<TNode> n2 = ordered.get(1);

            w.write(String.format("%d %d %s l \"%s\"\n", n1.getId(), n2.getId(), Double.toString(e.getWeight()), e.getData().toString()));
        }
    }

    w.close();
}
项目:CustomWorldGen    文件:PlayerProfileCache.java   
/**
 * Save the cached profiles to disk
 */
public void save()
{
    String s = this.gson.toJson((Object)this.getEntriesWithLimit(1000));
    BufferedWriter bufferedwriter = null;

    try
    {
        bufferedwriter = Files.newWriter(this.usercacheFile, Charsets.UTF_8);
        bufferedwriter.write(s);
        return;
    }
    catch (FileNotFoundException var8)
    {
        ;
    }
    catch (IOException var9)
    {
        return;
    }
    finally
    {
        IOUtils.closeQuietly((Writer)bufferedwriter);
    }
}
项目:metanome-algorithms    文件:Benchmarker.java   
protected static final void writeMetaData(File resultFile, THashMap<String, String> cmdLine) {
    StringBuilder metaDataLineBuilder = new StringBuilder();
    for (String optionKey : cmdLine.keySet()) {
        if (cmdLine.get(optionKey) != null) {
            metaDataLineBuilder.append(String.format("# %s :\t%s\n", optionKey, cmdLine.get(optionKey)));
            System.out.print(String.format("# %s :\t%s\n", optionKey, cmdLine.get(optionKey)));
        } else {
            metaDataLineBuilder.append(String.format("# %s :\t%s\n", optionKey, "true"));
            System.out.print(String.format("# %s :\t%s\n", optionKey, "true"));
        }
    }
    metaDataLineBuilder.append("#Filename\t#Rows\t#Columns\tTime\t#Deps\t#<2Deps\t#<3Deps\t#<4Deps\t#<5Deps\t#<6Deps\t#>5Deps\t#Partitions\n");
    System.out.println("#Filename\t#Rows\t#Columns\tTime\t#Deps\t#<2Deps\t#<3Deps\t#<4Deps\t#<5Deps\t#<6Deps\t#>5Deps\t#Partitions\n");
    try {
        BufferedWriter resultFileWriter = new BufferedWriter(new FileWriter(resultFile));
        resultFileWriter.write(metaDataLineBuilder.toString());
        resultFileWriter.close();
    } catch (IOException e) {
        System.out.println("Couldn't write meta data.");
    }
}
项目:openjdk-jdk10    文件:DOMResultTest.java   
/**
 * Prints all node names, attributes to file
 * @param node a node that need to be recursively access.
 * @param bWriter file writer.
 * @throws IOException if writing file failed.
 */
private void writeNodes(Node node, BufferedWriter bWriter) throws IOException {
    String str = "Node: " + node.getNodeName();
    bWriter.write( str, 0,str.length());
    bWriter.newLine();

    NamedNodeMap nnm = node.getAttributes();
    if (nnm != null && nnm.getLength() > 0)
        for (int i=0; i<nnm.getLength(); i++) {
            str = "AttributeName:" + ((Attr) nnm.item(i)).getName() +
                  ", AttributeValue:" +((Attr) nnm.item(i)).getValue();
            bWriter.write( str, 0,str.length());
            bWriter.newLine();
        }

    NodeList kids = node.getChildNodes();
    if (kids != null)
        for (int i=0; i<kids.getLength(); i++)
            writeNodes(kids.item(i), bWriter);
}
项目:KakaoBot    文件:FileManager.java   
public static Object readData(Type.Project project, String key) {
    File root = getProjectFile(project);
    File data = new File(root, "data.json");

    try {
        BufferedReader reader = new BufferedReader(new FileReader(data));
        BufferedWriter writer = new BufferedWriter(new FileWriter(data));

        String line;
        JSONObject json = new JSONObject();
        while((line = reader.readLine()) != null) {
            JSONObject object = new JSONObject(line);
            if(object.has(key)) {
                return object.get(key);
            }
        }
        writer.write(json.toString());
    } catch(IOException err) {}
    catch (JSONException e) {
        e.printStackTrace();
    }

    return null;
}
项目:geomapapp    文件:MapApp.java   
public void updatePortal(String portalUpdatedTime) throws IOException {
    // delete text file
    if (portalSelectFile.exists()) {
        portalSelectFile.delete();
    }

    // delete old .dat file
    if (portalSelectFileOld.exists()) {
        portalSelectFileOld.delete();
    }

    // make and update new file
    menusCacheDir.mkdirs();
    portalSelectFile.createNewFile();

    // Put in new values just mb for now from server
    BufferedWriter outMB = new BufferedWriter( new FileWriter(portalSelectFile, false) );
    outMB.write(portalUpdatedTime);
    outMB.close();
}
项目:hadoop-oss    文件:TestConfiguration.java   
public void testTrim() throws IOException {
  out=new BufferedWriter(new FileWriter(CONFIG));
  startConfig();
  String[] whitespaces = {"", " ", "\n", "\t"};
  String[] name = new String[100];
  for(int i = 0; i < name.length; i++) {
    name[i] = "foo" + i;
    StringBuilder prefix = new StringBuilder(); 
    StringBuilder postfix = new StringBuilder(); 
    for(int j = 0; j < 3; j++) {
      prefix.append(whitespaces[RAN.nextInt(whitespaces.length)]);
      postfix.append(whitespaces[RAN.nextInt(whitespaces.length)]);
    }

    appendProperty(prefix + name[i] + postfix, name[i] + ".value");
  }
  endConfig();

  conf.addResource(new Path(CONFIG));
  for(String n : name) {
    assertEquals(n + ".value", conf.get(n));
  }
}
项目:Scraping-AvvisiDMI    文件:FileManager.java   
public static void scrivi(File file, String string) throws IOException {
    FileWriter fw = new FileWriter(file);
    BufferedWriter bw = new BufferedWriter(fw);
    bw.write(string+"\n");
    bw.flush();
    bw.close();
}
项目:incubator-netbeans    文件:TrieDictionaryTest.java   
private Dictionary constructTrie(SortedSet<String> data) throws Exception {
    clearWorkDir();

    File sourceFile = new File(getWorkDir(), "source");
    Writer w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(sourceFile), "UTF-8"));

    for (String d : data) {
        w.write(d);
        w.write("\n");
    }

    w.close();

    File trieFile = new File(getWorkDir(), "dict");

    return TrieDictionary.getDictionary(trieFile, Collections.<URL>singletonList(sourceFile.toURI().toURL()));
}
项目:Botanist    文件:DiseaseParser.java   
/**
 * Create a parser for diseases file
 * @param inputFileName - plant disease csv
 * @param outputFileName - firebase .json
 * @throws IOException if a read/write error occurs
 */
public DiseaseParser(String inputFileName, String outputFileName) throws IOException {
    input = new File(inputFileName);
    output = new File(outputFileName);
    br = new BufferedReader(new FileReader(input));
    bw = new BufferedWriter(new FileWriter(output));
    familyDiseaseMap = new HashMap<String, List<String>>();
    diseaseUrls = parseDiseaseUrls(DISEASE_REFS_FILE);
}
项目:rejoiner    文件:LibraryProtoWriter.java   
public static void main(String[] args) throws IOException {
  if (args.length == 0) {
    throw new RuntimeException("output path required");
  }
  String proto = SchemaToProto.toProto(LibrarySchema.SCHEMA);
  BufferedWriter writer = Files.newWriter(new File(args[0]), Charsets.UTF_8);
  try {
    writer.write(proto);
  } finally {
    writer.close();
  }
}
项目:bStats-Metrics    文件:Metrics.java   
/**
 * 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 :)");
    }
}
项目:gretl    文件:SqlExecutorStepTest.java   
private File createSqlFileWithWrongExtension() throws Exception{
    File sqlFile =  folder.newFile("query.txt");
    BufferedWriter writer = new BufferedWriter(new FileWriter(sqlFile));
    writer.write(" INSERT INTO colors\n" +
            "VALUES (124,252,0,'LawnGreen')");
    writer.close();
    return sqlFile;
}
项目:hadoop    文件:TestConfiguration.java   
/**
 * Tests use of multi-byte characters in property names and values.  This test
 * round-trips multi-byte string literals through saving and loading of config
 * and asserts that the same values were read.
 */
public void testMultiByteCharacters() throws IOException {
  String priorDefaultEncoding = System.getProperty("file.encoding");
  try {
    System.setProperty("file.encoding", "US-ASCII");
    String name = "multi_byte_\u611b_name";
    String value = "multi_byte_\u0641_value";
    out = new BufferedWriter(new OutputStreamWriter(
      new FileOutputStream(CONFIG_MULTI_BYTE), "UTF-8"));
    startConfig();
    declareProperty(name, value, value);
    endConfig();

    Configuration conf = new Configuration(false);
    conf.addResource(new Path(CONFIG_MULTI_BYTE));
    assertEquals(value, conf.get(name));
    FileOutputStream fos = new FileOutputStream(CONFIG_MULTI_BYTE_SAVED);
    try {
      conf.writeXml(fos);
    } finally {
      IOUtils.closeStream(fos);
    }

    conf = new Configuration(false);
    conf.addResource(new Path(CONFIG_MULTI_BYTE_SAVED));
    assertEquals(value, conf.get(name));
  } finally {
    System.setProperty("file.encoding", priorDefaultEncoding);
  }
}
项目:RefDiff    文件:LSDRuleEnumerator.java   
public LSDRuleEnumerator(File twoKBFile, File deltaKBFile,
        File winnowingRulesFile, File resultsFile, int minConcFact,
        double accuracy, int k, int beamSize2, int maxException,
        File modifiedWinnowingRulesFile, BufferedWriter output)
        throws Exception {
    setMinMatchesPerLiteral(0);
    setMaxExceptions(maxException);
    setBeamSize(beamSize);
    setMinMatches(minConcFact);
    setMinAccuracy(accuracy);
    setAntecedentSize(k);
    this.output = output;
    this.fb = new LSDFactBase();
    // reads input files and builds lists of facts
    startTimer();
    read2kbFacts = new LSDTyrubaFactReader(twoKBFile).getFacts();
    readDeltaFacts = new LSDTyrubaFactReader(deltaKBFile).getFacts();
    winnowingRules = new LSDAlchemyRuleReader(winnowingRulesFile)
            .getRules();

    // set onDemand database manipulators
    onDemand2KB = new LSdiffDistanceFactBase(read2kbFacts, readDeltaFacts);
    onDemandDeltaKB = new LSdiffHierarchialDeltaKB(readDeltaFacts);

    // set the modified winnowing rules
    modifiedWinnowingRules = new LSDAlchemyRuleReader(new File(
            MetaInfo.modifiedWinnowings)).getRules();
    stopTimer();
}
项目:SER316-Dresden    文件:LoadableProperties.java   
public void save(OutputStream outStream) throws IOException {
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream, "UTF-8"));
    String aKey;
    Object aValue;
    for (Enumeration e = keys(); e.hasMoreElements();) {
        aKey = (String) e.nextElement();
        aValue = get(aKey);
        out.write(aKey + " = " + aValue);
        out.newLine();
    }
    out.flush();
    out.close();
}
项目:KernelHive    文件:WorkflowEditorDropTargetListener.java   
private List<IKernelFile> copyKernelsFromTemplates(
        final KernelRepositoryEntry kre, final File rootDir)
        throws SecurityException, IOException {
    final List<IKernelFile> sourceFiles = new ArrayList<IKernelFile>(kre
            .getKernelPaths().size());
    for (final KernelPathEntry kpe : kre.getKernelPaths()) {
        final BufferedReader br = new BufferedReader(new InputStreamReader(
                kpe.getPath().openConnection().getInputStream()));

        final File file = FileUtils.createNewFile(rootDir.getAbsolutePath()
                + System.getProperty("file.separator") + kpe.getName());

        final BufferedWriter bw = new BufferedWriter(new FileWriter(file));

        String line = br.readLine();
        while (line != null) {
            bw.write(line);
            bw.newLine();
            line = br.readLine();
        }
        bw.flush();
        bw.close();
        br.close();

        sourceFiles.add(new KernelFile(file, kpe.getId(), kpe
                .getProperties()));
    }
    return sourceFiles;
}