List of usage examples for java.io BufferedWriter BufferedWriter
public BufferedWriter(Writer out)
From source file:jgnash.convert.exportantur.csv.CsvExport.java
public static void exportAccount(final Account account, final LocalDate startDate, final LocalDate endDate, final File file) { Objects.requireNonNull(account); Objects.requireNonNull(startDate); Objects.requireNonNull(endDate); Objects.requireNonNull(file); // force a correct file extension final String fileName = FileUtils.stripFileExtension(file.getAbsolutePath()) + ".csv"; final CSVFormat csvFormat = CSVFormat.EXCEL.withQuoteMode(QuoteMode.ALL); try (final OutputStreamWriter outputStreamWriter = new OutputStreamWriter( Files.newOutputStream(Paths.get(fileName)), StandardCharsets.UTF_8); final CSVPrinter writer = new CSVPrinter(new BufferedWriter(outputStreamWriter), csvFormat)) { outputStreamWriter.write('\ufeff'); // write UTF-8 byte order mark to the file for easier imports writer.printRecord("Account", "Number", "Debit", "Credit", "Balance", "Date", "Timestamp", "Memo", "Payee", "Reconciled"); // write the transactions final List<Transaction> transactions = account.getTransactions(startDate, endDate); final DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder().appendValue(YEAR, 4) .appendValue(MONTH_OF_YEAR, 2).appendValue(DAY_OF_MONTH, 2).toFormatter(); final DateTimeFormatter timestampFormatter = new DateTimeFormatterBuilder().appendValue(YEAR, 4) .appendLiteral('-').appendValue(MONTH_OF_YEAR, 2).appendLiteral('-') .appendValue(DAY_OF_MONTH, 2).appendLiteral(' ').appendValue(HOUR_OF_DAY, 2).appendLiteral(':') .appendValue(MINUTE_OF_HOUR, 2).appendLiteral(':').appendValue(SECOND_OF_MINUTE, 2) .toFormatter();//from w ww . j ava 2 s . c om for (final Transaction transaction : transactions) { final String date = dateTimeFormatter.format(transaction.getLocalDate()); final String timeStamp = timestampFormatter.format(transaction.getTimestamp()); final String credit = transaction.getAmount(account).compareTo(BigDecimal.ZERO) < 0 ? "" : transaction.getAmount(account).abs().toPlainString(); final String debit = transaction.getAmount(account).compareTo(BigDecimal.ZERO) > 0 ? "" : transaction.getAmount(account).abs().toPlainString(); final String balance = account.getBalanceAt(transaction).toPlainString(); final String reconciled = transaction.getReconciled(account) == ReconciledState.NOT_RECONCILED ? Boolean.FALSE.toString() : Boolean.TRUE.toString(); writer.printRecord(account.getName(), transaction.getNumber(), debit, credit, balance, date, timeStamp, transaction.getMemo(), transaction.getPayee(), reconciled); } } catch (final IOException e) { Logger.getLogger(CsvExport.class.getName()).log(Level.SEVERE, e.getLocalizedMessage(), e); } }
From source file:com.mycompany.asyncreq.GetThread.java
@Override public void run() { try {//from www . j a v a2 s. c o m Future<HttpResponse> future = client.execute(request, context, null); HttpResponse response = future.get(); MatcherAssert.assertThat(response.getStatusLine().getReasonPhrase(), equals(200)); Boolean isDone = true; Scanner scan = new Scanner(System.in); File f = new File("my.txt"); FileWriter fr = new FileWriter(f); BufferedWriter bwr = new BufferedWriter(fr); BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); while ((br.readLine()) != null) { bwr.write(new Scanner(System.in).nextLine()); } } catch (Exception ex) { System.out.println(ex.getLocalizedMessage()); } }
From source file:de.ipbhalle.metfrag.main.CommandLineTool.java
/** * @param args/*w w w .j a v a 2s . com*/ * @throws Exception */ public static void main(String[] args) { CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); options.addOption("d", "database", true, "database: " + Databases.getString() + " (default: kegg)"); options.addOption("l", "localdb", true, "use a local database together with a settings file for candidate search (default: not used) note: only usable if pubchem database is selected (-d)"); options.addOption("a", "mzabs", true, "allowed absolute (Da) mass deviation of fragment and peak masses (default: 0.01)"); options.addOption("p", "mzppm", true, "allowed relative (ppm) mass deviation of fragment and peak masses (default: 10)"); options.addOption("s", "searchppm", true, "relative (ppm) mass deviation used for candidate search in given compound database (-d) (default: 10; not used by default if sdf database is selected (-d))\n"); options.addOption("n", "exactmass", true, "neutral mass of measured compound used for candidate search in database (-d) (mandatory)"); options.addOption("b", "biological", false, "only consider compounds including CHNOPS atoms (not used by default)"); options.addOption("i", "databaseids", true, "database ids of compounds used for in silico fragmentation (separated by ,) (not used by default; not used if sdf database is selected (-d)) note: given ids must be valid ids of given database (-d)"); options.addOption("t", "treedepth", true, "treedepth used for in silico fragmentation (default: 2) note: high values result in high computation time"); options.addOption("M", "mode", true, "mode used for measured ms/ms spectrum:\n" + Modes.getString() + "(default: 3)"); options.addOption("f", "formula", true, "molecular formula of measured compound used for candidate search in database (-d) (not used by default; not used if sdf database is selected (-d))"); options.addOption("B", "breakrings", false, "allow splitting of aromatic rings of candidate structures during in silico fragmentation (not used by default)"); options.addOption("F", "storefragments", false, "store in silico generated fragments of candidate molecules (not used by default)"); options.addOption("R", "resultspath", true, "directory where result files are stored (default: /tmp)"); options.addOption("L", "sdffile", true, "location of the local sdf file (mandatory if sdf database (-d) is selected)"); options.addOption("h", "help", false, "print help"); options.addOption("D", "spectrumfile", true, "file containing peak data (mandatory) note: commandline options overwrite parameters given in the spectrum data file"); options.addOption("T", "threads", true, "number of threads used for fragment calculation (default: number of available cpu cores)"); options.addOption("c", "chemspidertoken", true, "Token for ChemSpider database search (not used by default; only necessary (mandatory) if ChemSpider database (-d) is selected)"); options.addOption("v", "verbose", false, "get more output information during the processing (not used by default)"); options.addOption("S", "samplename", true, "name of the sample measured (mandatory) note: result files are stored with given value"); options.addOption("P", "saveparameters", false, "save used parameters (not used by default)"); options.addOption("e", "printexamplespecfile", false, "print an example spectrum data file (not used by default)"); options.addOption("C", "charge", true, "charge used in combination with mode (-M):\n" + Charges.getString() + " (default: 1)"); options.addOption("r", "range", true, "range of candidates that will be processed: N (first N), M-N (from M to N), M- (from M), -N (till N); if N is greater than the number of candidates it will be set accordingly"); // parse the command line arguments CommandLine line = null; try { line = parser.parse(options, args); } catch (ParseException e1) { System.out.println(e1.getMessage()); System.out.println("Error: Could not parse option parameters."); System.out.println("Use help -h (--help) for information."); System.exit(1); } if (line == null) { System.out.println("Error: Could not parse option parameters."); System.out.println("Use help -h (--help) for information."); System.exit(1); } if (checkInitialParamsPresent(line, options)) System.exit(0); if (!checkSpectrumFile(line)) { System.out.println("Error: Option parameters are not set correctly."); System.out.println("Use help -h (--help) for information."); System.exit(1); } if (!parseSpectrumFile(spectrumfile)) { System.out.println("Error: Could not correctly parse the spectrum data file."); System.out.println("Use help -h (--help) for information."); System.exit(1); } int successfulSet = setParameters(line, options); if (successfulSet == 2) System.exit(0); if (successfulSet != 0) { System.out.println("Error: Option parameters are not set correctly."); System.out.println("Use help -h (--help) for information."); System.exit(1); } boolean successfulChecked = true; if (successfulSet == 0) successfulChecked = checkParameters(); if (saveParametersIsSet) { try { BufferedWriter bwriter = new BufferedWriter(new FileWriter(new File( resultspath + System.getProperty("file.separator") + "parameters_" + sampleName + ".txt"))); bwriter.write(getParameters()); bwriter.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { boolean isPositive = true; if (charge.getValue() == 2) isPositive = false; spec = new WrapperSpectrum(peaksString, mode.getValueWithOffset(), exactMass.getValue(), isPositive); } catch (Exception e) { System.out.println("Error: Could not parse spectrum correctly. Check the given peak list."); System.exit(1); } if (!successfulChecked) { System.out.println("Error: Option parameters are not set correctly."); System.out.println("Use help -h (--help) for information."); System.exit(1); } List<MetFragResult> results = null; String pathToStoreFrags = ""; if (storeFragments) pathToStoreFrags = resultspath; //run metfrag when all checks were successful if (usesdf) { try { if (verbose) { System.out.println("start fragmenter with local database"); System.out.println("using database " + database); } results = MetFrag.startConvenienceSDF(spec, mzabs.getValue(), mzppm.getValue(), searchppm.getValue(), true, breakRings, treeDepth.getValue(), true, true, true, false, Integer.MAX_VALUE, true, sdfFile, "", null, searchppmIsSet, pathToStoreFrags, numberThreads.getValue(), verbose, sampleName, onlyBiologicalCompounds); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); System.out.println("Error: Could not perform in silico fragmentation step."); System.exit(1); } } else { try { if (verbose) { if (!localdbIsSet) System.out.println("start fragmenter with web database"); else System.out.println("start fragmenter with local database"); System.out.println("using database " + database); } results = MetFrag.startConvenience(database, databaseIDs, formula, exactMass.getValue(), spec, useProxy, mzabs.getValue(), mzppm.getValue(), searchppm.getValue(), true, breakRings, treeDepth.getValue(), true, false, true, false, startindex.getValue(), endindex.getValue(), true, pathToStoreFrags, numberThreads.getValue(), chemSpiderToken, verbose, sampleName, localdb, onlyBiologicalCompounds, dblink, dbuser, dbpass, uniquebyinchi); } catch (Exception e) { e.printStackTrace(); System.out.println("Error: " + e.getMessage()); System.out.println("Error: Could not perform in silico fragmentation step."); System.exit(1); } } saveResults(results); }
From source file:com.wso2telco.services.bw.FileUtil.java
public static void fileWrite(String filePath, String data) throws IOException { BufferedWriter out = null;//from w w w. j a v a 2 s. co m try { out = new BufferedWriter(new FileWriter(filePath)); out.write(data); } catch (IOException e) { e.printStackTrace(); } finally { out.close(); } }
From source file:WarUtil.java
private static void writeLastModifiled(File file, long time) { BufferedWriter writer = null; try {//from ww w . ja va2s . com if (!file.exists()) { file.createNewFile(); } writer = new BufferedWriter(new FileWriter(file)); writer.write(Long.toString(time)); writer.flush(); } catch (Exception e) { } }
From source file:net.genesishub.gFeatures.Plus.Skript.SkriptManager.java
public void Enable(Extension s, String packages) throws IOException { try {/*from w w w.j a v a 2 s . c o m*/ Reader paramReader = new InputStreamReader(getClass().getResourceAsStream( "/net/genesishub/gFeatures/Plus/Skript/" + packages + "/" + s.getName() + ".sk")); StringWriter writer = new StringWriter(); IOUtils.copy(paramReader, writer); String theString = writer.toString(); File f = new File("plugins/Skript/scripts/" + s.toString() + ".sk"); f.createNewFile(); BufferedWriter bw = new BufferedWriter(new FileWriter(f, true)); bw.write(theString); bw.close(); } catch (Exception E) { } }
From source file:de.hska.ld.core.config.LDLoggerConfig.java
@Autowired private void init() throws IOException { File f = File.createTempFile("tinylog_conf", ".txt"); FileOutputStream fos = new FileOutputStream(f); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos)); try {/*from ww w .jav a 2 s. c o m*/ String writer = env.getProperty("tinylog.writer"); bw.write("tinylog.writer = " + writer); bw.newLine(); /*String fileName = env.getProperty("tinylog.writer.filename"); bw.write("tinylog.writer.filename = " + fileName); bw.newLine(); String buffered = env.getProperty("tinylog.writer.buffered"); bw.write("tinylog.writer.buffered = " + buffered); bw.newLine(); String append = env.getProperty("tinylog.writer.append"); bw.write("tinylog.writer.append = " + append); bw.newLine();*/ String level = env.getProperty("tinylog.level"); bw.write("tinylog.level = " + level); bw.newLine(); String writerUrl = env.getProperty("tinylog.writer.url"); bw.write("tinylog.writer.url = " + writerUrl); bw.newLine(); String writerTable = env.getProperty("tinylog.writer.table"); bw.write("tinylog.writer.table = " + writerTable); bw.newLine(); String writerColumns = env.getProperty("tinylog.writer.columns"); bw.write("tinylog.writer.columns = " + writerColumns); bw.newLine(); String writerValues = env.getProperty("tinylog.writer.values"); bw.write("tinylog.writer.values = " + writerValues); bw.newLine(); String writerBatch = env.getProperty("tinylog.writer.batch"); bw.write("tinylog.writer.batch = " + writerBatch); bw.newLine(); String writerUsername = env.getProperty("tinylog.writer.username"); bw.write("tinylog.writer.username = " + writerUsername); bw.newLine(); String writerPassword = env.getProperty("tinylog.writer.password"); bw.write("tinylog.writer.password = " + writerPassword); bw.newLine(); String writingThread = env.getProperty("tinylog.writingthread"); bw.write("tinylog.writingthread = " + writingThread); bw.newLine(); String wTObserve = env.getProperty("tinylog.writingthread.observe"); bw.write("tinylog.writingthread.observe = " + wTObserve); bw.newLine(); String wTPriority = env.getProperty("tinylog.writingthread.priority"); bw.write("writingthread.priority = " + wTPriority); } catch (Exception e) { e.printStackTrace(); } finally { bw.close(); } Configurator.fromFile(f).activate(); }
From source file:jmc.util.UtlFbComents.java
public static void getComentarios(Long idContenido, Long numComents) throws JMCException { File f = null;/*from w w w . j a v a 2 s . com*/ try { Properties props = ConfigPropiedades.getProperties("props_config.properties"); CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL)); URL ur = new URL("http://graph.facebook.com/comments?id=" + Contenido.getContenido("Where cont_id = '" + idContenido + "'").get(0).getEnlaceURL() + "&limit=" + numComents + "&filter=stream"); HttpURLConnection cn = (HttpURLConnection) ur.openConnection(); cn.setRequestProperty("user-agent", props.getProperty("navegador")); cn.setInstanceFollowRedirects(false); cn.setUseCaches(false); cn.connect(); BufferedReader br = new BufferedReader(new InputStreamReader(cn.getInputStream())); String dirTempHtml = props.getProperty("archive_json") + "/"; File fld = new File(dirTempHtml); boolean creado = fld.exists() ? true : fld.mkdir(); if (creado) { String archFile = idContenido + ".json"; String archivo = dirTempHtml + archFile; String linea = null; f = new File(archivo); BufferedWriter bw = new BufferedWriter(new FileWriter(f)); while ((linea = br.readLine()) != null) { bw.append(linea); } bw.close(); cn.disconnect(); List<Fbcoment> lfb = Convertidor.getFbcomentObjects(idContenido, archivo); Fbcoment.actComents(idContenido, lfb); } else { cn.disconnect(); } } catch (IOException e) { throw new JMCException(e); } }
From source file:com.pcms.temp.generate.MarkeWrite.java
public void save(String savePath, String templateName, String templateEncoding, Map<?, ?> root) { String path = savePath + "/" + templateName + ".html"; FileUtil.delete(path);/* w ww . jav a 2 s.c o m*/ try { File file = FileUtil.createFile(path); Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))); this.processTemplate(templateName, templateEncoding, root, out); } catch (FileNotFoundException ex) { _log.error(ex.getMessage()); } catch (IOException ex) { _log.error(ex.getMessage()); } }
From source file:m3umaker.exFiles.java
public void genFile(String M3UfileName, List Files) { try {// w ww . j a va 2 s. c o m BufferedWriter out = new BufferedWriter(new FileWriter(mDIR + "\\" + M3UfileName + ".m3u", true)); // System.out.println("----" + mDIR + M3UfileName); for (int i = 0; i < Files.size(); i++) { out.write(Files.get(i).toString()); out.newLine(); } out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } }