Java Code Examples for java.io.BufferedWriter

The following are top voted examples for showing how to use java.io.BufferedWriter. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: BookReader-master   File: LogUtils.java   View source code 7 votes vote down vote up
/**
 * 打开日志文件并写入日志
 *
 * @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();
    }
}
 
Example 2
Project: FastReading   File: FileReadingAndWriting.java   View source code 7 votes vote down vote up
@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;
}
 
Example 3
Project: pre-dem-android   File: LogUtils.java   View source code 7 votes vote down vote up
/**
 * 打印信息
 *
 * @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");
    }
}
 
Example 4
Project: powsybl-core   File: CacheManager.java   View source code 7 votes vote down vote up
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;
}
 
Example 5
Project: hadoop   File: FSNamesystem.java   View source code 6 votes vote down vote up
/**
 * 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();
  }
}
 
Example 6
Project: hanlpStudy   File: TMDictionaryMaker.java   View source code 6 votes vote down vote up
@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;
}
 
Example 7
Project: gate-core   File: DocumentStaxUtils.java   View source code 6 votes vote down vote up
/**
 * 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
}
 
Example 8
Project: Coder   File: DiskLruCache.java   View source code 6 votes vote down vote up
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);
  }
}
 
Example 9
Project: UaicNlpToolkit   File: PrecompileFromDexOnlineDB.java   View source code 6 votes vote down vote up
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)");
}
 
Example 10
Project: pac4j-plus   File: CasRestAuthenticator.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 11
Project: OpenVSP3Plugin   File: OpenVSP3Plugin.java   View source code 6 votes vote down vote up
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();
}
 
Example 12
Project: Reer   File: JavadocOptionFileWriter.java   View source code 6 votes vote down vote up
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);
        }
    });
}
 
Example 13
Project: Military-North-Compass   File: Compass.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 14
Project: permission-map   File: OutputGraph.java   View source code 6 votes vote down vote up
/**
 * 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();
  
}
 
Example 15
Project: ditb   File: ResultParser2.java   View source code 6 votes vote down vote up
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();
}
 
Example 16
Project: JATS2LaTeX   File: BodyStandard.java   View source code 6 votes vote down vote up
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();

}
 
Example 17
Project: tablasco   File: ExceptionHtml.java   View source code 6 votes vote down vote up
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));
    }
}
 
Example 18
Project: ArtOfAndroid   File: TCPServerService.java   View source code 6 votes vote down vote up
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();
}
 
Example 19
Project: SaveableSerializing   File: SaveableDataWriter.java   View source code 6 votes vote down vote up
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){}
}
 
Example 20
Project: lodrecsys_eswc2017tutorial   File: Convert2mymedialite.java   View source code 6 votes vote down vote up
/**
 * 
 * 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);
        }
    }
}
 
Example 21
Project: hadoop   File: TestConfiguration.java   View source code 6 votes vote down vote up
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));
}
 
Example 22
Project: JavaPlot   File: FileUtils.java   View source code 6 votes vote down vote up
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();
}
 
Example 23
Project: LoRaWAN-Smart-Parking   File: HttpResponseCache.java   View source code 6 votes vote down vote up
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();
}
 
Example 24
Project: winter   File: Graph.java   View source code 6 votes vote down vote up
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();
}
 
Example 25
Project: CustomWorldGen   File: PlayerProfileCache.java   View source code 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 26
Project: metanome-algorithms   File: Benchmarker.java   View source code 6 votes vote down vote up
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.");
	}
}
 
Example 27
Project: openjdk-jdk10   File: DOMResultTest.java   View source code 6 votes vote down vote up
/**
 * 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);
}
 
Example 28
Project: KakaoBot   File: FileManager.java   View source code 6 votes vote down vote up
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;
}
 
Example 29
Project: geomapapp   File: MapApp.java   View source code 6 votes vote down vote up
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();
}
 
Example 30
Project: hadoop-oss   File: TestConfiguration.java   View source code 6 votes vote down vote up
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));
  }
}
 
Example 31
Project: Scraping-AvvisiDMI   File: FileManager.java   View source code 6 votes vote down vote up
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();
}
 
Example 32
Project: incubator-netbeans   File: TrieDictionaryTest.java   View source code 6 votes vote down vote up
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()));
}
 
Example 33
Project: Botanist   File: DiseaseParser.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 34
Project: rejoiner   File: LibraryProtoWriter.java   View source code 5 votes vote down vote up
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();
  }
}
 
Example 35
Project: bStats-Metrics   File: Metrics.java   View source code 5 votes vote down vote up
/**
 * Writes a String to a file. It also adds a note for the user,
 *
 * @param file The file to write to. Cannot be null.
 * @param text The text to write.
 * @throws IOException If something did not work :(
 */
private void writeFile(File file, String text) throws IOException {
    if (!file.exists()) {
        file.createNewFile();
    }
    try (
            FileWriter fileWriter = new FileWriter(file);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)
    ) {
        bufferedWriter.write(text);
        bufferedWriter.newLine();
        bufferedWriter.write("Note: This class only exists for internal purpose. You can ignore it :)");
    }
}
 
Example 36
Project: gretl   File: SqlExecutorStepTest.java   View source code 5 votes vote down vote up
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;
}
 
Example 37
Project: hadoop   File: TestConfiguration.java   View source code 5 votes vote down vote up
/**
 * 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);
  }
}
 
Example 38
Project: RefDiff   File: LSDRuleEnumerator.java   View source code 5 votes vote down vote up
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();
}
 
Example 39
Project: SER316-Dresden   File: LoadableProperties.java   View source code 5 votes vote down vote up
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();
}
 
Example 40
Project: KernelHive   File: WorkflowEditorDropTargetListener.java   View source code 5 votes vote down vote up
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;
}