java类java.io.BufferedWriter的实例源码

LogUtils.java 文件源码 项目:BookReader-master 阅读 30 收藏 0 点赞 0 评论 0
/**
 * 打开日志文件并写入日志
 *
 * @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();
    }
}
FileReadingAndWriting.java 文件源码 项目:FastReading 阅读 18 收藏 0 点赞 0 评论 0
@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;
}
LogUtils.java 文件源码 项目:pre-dem-android 阅读 28 收藏 0 点赞 0 评论 0
/**
 * 打印信息
 *
 * @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");
    }
}
CacheManager.java 文件源码 项目:powsybl-core 阅读 31 收藏 0 点赞 0 评论 0
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;
}
FSNamesystem.java 文件源码 项目:hadoop 阅读 27 收藏 0 点赞 0 评论 0
/**
 * 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();
  }
}
TMDictionaryMaker.java 文件源码 项目:hanlpStudy 阅读 23 收藏 0 点赞 0 评论 0
@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;
}
DocumentStaxUtils.java 文件源码 项目:gate-core 阅读 29 收藏 0 点赞 0 评论 0
/**
 * 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
}
DiskLruCache.java 文件源码 项目:Coder 阅读 27 收藏 0 点赞 0 评论 0
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);
  }
}
PrecompileFromDexOnlineDB.java 文件源码 项目:UaicNlpToolkit 阅读 35 收藏 0 点赞 0 评论 0
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)");
}
CasRestAuthenticator.java 文件源码 项目:pac4j-plus 阅读 18 收藏 0 点赞 0 评论 0
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.java 文件源码 项目:OpenVSP3Plugin 阅读 20 收藏 0 点赞 0 评论 0
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();
}
JavadocOptionFileWriter.java 文件源码 项目:Reer 阅读 22 收藏 0 点赞 0 评论 0
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);
        }
    });
}
Compass.java 文件源码 项目:Military-North-Compass 阅读 29 收藏 0 点赞 0 评论 0
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);
    }
}
OutputGraph.java 文件源码 项目:permission-map 阅读 24 收藏 0 点赞 0 评论 0
/**
 * 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();

}
ResultParser2.java 文件源码 项目:ditb 阅读 24 收藏 0 点赞 0 评论 0
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();
}
BodyStandard.java 文件源码 项目:JATS2LaTeX 阅读 31 收藏 0 点赞 0 评论 0
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();

}
ExceptionHtml.java 文件源码 项目:tablasco 阅读 20 收藏 0 点赞 0 评论 0
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));
    }
}
TCPServerService.java 文件源码 项目:ArtOfAndroid 阅读 29 收藏 0 点赞 0 评论 0
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();
}
SaveableDataWriter.java 文件源码 项目:SaveableSerializing 阅读 20 收藏 0 点赞 0 评论 0
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){}
}
Convert2mymedialite.java 文件源码 项目:lodrecsys_eswc2017tutorial 阅读 18 收藏 0 点赞 0 评论 0
/**
 * 
 * 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);
        }
    }
}
TestConfiguration.java 文件源码 项目:hadoop 阅读 37 收藏 0 点赞 0 评论 0
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));
}
FileUtils.java 文件源码 项目:JavaPlot 阅读 27 收藏 0 点赞 0 评论 0
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();
}
HttpResponseCache.java 文件源码 项目:LoRaWAN-Smart-Parking 阅读 20 收藏 0 点赞 0 评论 0
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();
}
Graph.java 文件源码 项目:winter 阅读 27 收藏 0 点赞 0 评论 0
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();
}
PlayerProfileCache.java 文件源码 项目:CustomWorldGen 阅读 38 收藏 0 点赞 0 评论 0
/**
 * 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);
    }
}
Benchmarker.java 文件源码 项目:metanome-algorithms 阅读 30 收藏 0 点赞 0 评论 0
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.");
    }
}
DOMResultTest.java 文件源码 项目:openjdk-jdk10 阅读 22 收藏 0 点赞 0 评论 0
/**
 * 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);
}
FileManager.java 文件源码 项目:KakaoBot 阅读 34 收藏 0 点赞 0 评论 0
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;
}
MapApp.java 文件源码 项目:geomapapp 阅读 29 收藏 0 点赞 0 评论 0
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();
}
TestConfiguration.java 文件源码 项目:hadoop-oss 阅读 28 收藏 0 点赞 0 评论 0
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));
  }
}


问题


面经


文章

微信
公众号

扫码关注公众号