List of usage examples for java.nio.file Files newBufferedWriter
public static BufferedWriter newBufferedWriter(Path path, Charset cs, OpenOption... options) throws IOException
From source file:daylightchart.daylightchart.calculation.RiseSetUtility.java
/** * Writes chart calculations to a file.//from w ww. j a v a 2 s .c o m * * @param location * Location * @return File that was written */ public static Path writeCalculationsToFile(final Location location) { try { final Path file = Paths.get(location.getDescription() + ".txt").toAbsolutePath(); final Writer writer = Files.newBufferedWriter(file, WRITE, TRUNCATE_EXISTING); writeCalculations(writer, location); return file; } catch (final IOException e) { LOGGER.log(Level.WARNING, "Cannot write calculations for location " + location, e); return null; } }
From source file:sadl.utils.IoUtils.java
public static void writeToFile(double[] testSample, Path classificationTestFile) throws IOException { try (BufferedWriter bw = Files.newBufferedWriter(classificationTestFile, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) { bw.append(Arrays.toString(testSample).replace('[', ' ').replace(']', ' ')); bw.append('\n'); }//w w w .j a va 2 s. c o m }
From source file:sadl.utils.IoUtils.java
public static void writeToFile(List<double[]> testSamples, Path classificationTestFile) throws IOException { try (BufferedWriter bw = Files.newBufferedWriter(classificationTestFile, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) { for (final double[] testSample : testSamples) { bw.append(Arrays.toString(testSample).replace('[', ' ').replace(']', ' ')); bw.append('\n'); }/*from w w w.ja va2 s.co m*/ } }
From source file:net.fatlenny.datacitation.service.GitCitationDBService.java
@Override public Status saveQuery(Query query) throws CitationDBException { checkoutBranch(REF_QUERIES);/* w ww.j a v a 2s . c o m*/ String pidIdentifier = query.getPid().getIdentifier(); String fileName = DigestUtils.sha1Hex(pidIdentifier) + "." + QUERY_ENDING; try (Git git = new Git(repository)) { Path filePath = Paths.get(getWorkingTreeDir(), fileName); Properties properties = writeQueryToProperties(query); properties.store( Files.newBufferedWriter(filePath, StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW), ""); git.add().addFilepattern(fileName).call(); PersonIdent personIdent = new PersonIdent("ReCitable", "recitable@fatlenny.net"); String message = String.format("Created query file for PID=%s", pidIdentifier); git.commit().setMessage(message).setAuthor(personIdent).setCommitter(personIdent).call(); } catch (IOException | GitAPIException e) { throw new CitationDBException(e); } return Status.SUCCESS; }
From source file:de.huberlin.wbi.cuneiform.core.cre.LocalThread.java
@Override public void run() { Path scriptFile, location, successMarker, reportFile, callLocation, stdErrFile, stdOutFile; // Path lockMarker; Process process;// w w w. j a v a 2 s. c o m int exitValue; Set<JsonReportEntry> report; JsonReportEntry entry; String line; StringBuffer buf; Path srcPath, destPath; ProcessBuilder processBuilder; Ticket ticket; String script, stdOut, stdErr; long tic, toc; JSONObject obj; Message msg; Charset cs; int trial; boolean suc; Exception ex; if (log.isDebugEnabled()) log.debug("Starting up local thread for ticket " + invoc.getTicketId() + "."); if (invoc == null) throw new NullPointerException("Invocation must not be null."); ticket = invoc.getTicket(); process = null; stdOut = null; stdErr = null; // lockMarker = null; script = null; successMarker = null; cs = Charset.forName("UTF-8"); try { callLocation = Paths.get(System.getProperty("user.dir")); location = buildDir.resolve(String.valueOf(invoc.getTicketId())); // lockMarker = location.resolve( Invocation.LOCK_FILENAME ); successMarker = location.resolve(Invocation.SUCCESS_FILENAME); reportFile = location.resolve(Invocation.REPORT_FILENAME); script = invoc.toScript(); // if( Files.exists( lockMarker ) ) // throw new IOException( "Lock held on ticket "+invoc.getTicketId() ); if (!Files.exists(successMarker)) { deleteIfExists(location); Files.createDirectories(location); // Files.createFile( lockMarker ); scriptFile = invoc.getExecutablePath(location); Files.createFile(scriptFile, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwxr-x---"))); // write executable script try (BufferedWriter writer = Files.newBufferedWriter(scriptFile, cs, StandardOpenOption.CREATE)) { writer.write(script); } // write executable log entry try (BufferedWriter writer = Files.newBufferedWriter(reportFile, cs, StandardOpenOption.CREATE)) { writer.write(ticket.getExecutableLogEntry().toString()); writer.write('\n'); } for (String filename : invoc.getStageInList()) { if (filename.charAt(0) == '/') throw new UnsupportedOperationException("Absolute path encountered '" + filename + "'."); srcPath = centralRepo.resolve(filename); destPath = location.resolve(filename); if (!Files.exists(srcPath)) { srcPath = callLocation.resolve(filename); if (log.isTraceEnabled()) log.trace("Resolving relative path '" + srcPath + "'."); } else if (log.isTraceEnabled()) log.trace("Resolving path to central repository '" + srcPath + "'."); if (log.isTraceEnabled()) log.trace("Trying to create symbolic link from '" + srcPath + "' to '" + destPath + "'."); if (!Files.exists(destPath.getParent())) Files.createDirectories(destPath.getParent()); Files.createSymbolicLink(destPath, srcPath); } // run script processBuilder = new ProcessBuilder(invoc.getCmd()); processBuilder.directory(location.toFile()); stdOutFile = location.resolve(Invocation.STDOUT_FILENAME); stdErrFile = location.resolve(Invocation.STDERR_FILENAME); processBuilder.redirectOutput(stdOutFile.toFile()); processBuilder.redirectError(stdErrFile.toFile()); trial = 1; suc = false; ex = null; tic = System.currentTimeMillis(); do { try { process = processBuilder.start(); suc = true; } catch (IOException e) { ex = e; if (log.isWarnEnabled()) log.warn("Unable to start process on trial " + (trial++) + " Waiting " + WAIT_INTERVAL + "ms: " + e.getMessage()); Thread.sleep(WAIT_INTERVAL); } } while (suc == false && trial <= MAX_TRIALS); if (process == null) { ticketSrc.sendMsg(new TicketFailedMsg(cre, ticket, ex, script, null, null)); // Files.delete( lockMarker ); return; } exitValue = process.waitFor(); toc = System.currentTimeMillis(); try (BufferedWriter writer = Files.newBufferedWriter(reportFile, cs, StandardOpenOption.APPEND)) { obj = new JSONObject(); obj.put(JsonReportEntry.LABEL_REALTIME, toc - tic); entry = invoc.createJsonReportEntry(tic, JsonReportEntry.KEY_INVOC_TIME, obj); writer.write(entry.toString()); writer.write('\n'); try (BufferedReader reader = Files.newBufferedReader(stdOutFile, cs)) { buf = new StringBuffer(); while ((line = reader.readLine()) != null) buf.append(line).append('\n'); stdOut = buf.toString(); if (!stdOut.isEmpty()) { entry = invoc.createJsonReportEntry(JsonReportEntry.KEY_INVOC_STDOUT, stdOut); writer.write(entry.toString()); writer.write('\n'); } } try (BufferedReader reader = Files.newBufferedReader(stdErrFile, cs)) { buf = new StringBuffer(); while ((line = reader.readLine()) != null) buf.append(line).append('\n'); stdErr = buf.toString(); if (!stdErr.isEmpty()) { entry = invoc.createJsonReportEntry(JsonReportEntry.KEY_INVOC_STDERR, stdErr); writer.write(entry.toString()); writer.write('\n'); } } if (exitValue == 0) Files.createFile(successMarker); else { ticketSrc.sendMsg(new TicketFailedMsg(cre, ticket, null, script, stdOut, stdErr)); // Files.delete( lockMarker ); return; } } } // gather report report = new HashSet<>(); try (BufferedReader reader = Files.newBufferedReader(reportFile, cs)) { while ((line = reader.readLine()) != null) { line = line.trim(); if (line.isEmpty()) continue; entry = new JsonReportEntry(line); // If the report comes from the hard cache then the run id // is different from the run id of this invocation. This is // corrected here. entry.setRunId(invoc.getRunId()); report.add(entry); } } invoc.evalReport(report); // create link in central data repository for (String f : invoc.getStageOutList()) { srcPath = location.resolve(f); destPath = centralRepo.resolve(f); if (Files.exists(destPath)) continue; if (log.isTraceEnabled()) log.trace("Creating link from " + srcPath + " to " + destPath + "."); Files.createSymbolicLink(destPath, srcPath); } ticketSrc.sendMsg(new TicketFinishedMsg(cre, invoc.getTicket(), report)); if (log.isTraceEnabled()) log.trace("Local thread ran through without exception."); // Files.deleteIfExists( lockMarker ); } catch (InterruptedException e) { if (log.isTraceEnabled()) log.trace("Local thread has been interrupted."); } catch (Exception e) { if (log.isTraceEnabled()) log.trace("Something went wrong. Deleting success marker if present."); if (successMarker != null) try { Files.deleteIfExists(successMarker); } catch (IOException e1) { e1.printStackTrace(); } msg = new TicketFailedMsg(cre, ticket, e, script, stdOut, stdErr); ticketSrc.sendMsg(msg); } finally { if (process != null) { if (log.isDebugEnabled()) log.debug("Stopping local thread for ticket " + invoc.getTicketId() + "."); process.destroy(); } } }
From source file:com.rvantwisk.cnctools.controllers.CNCToolsController.java
private void saveGCode(String gCode, final File filename) { if (gCode == null) { throw new IllegalArgumentException("gCode most not be null"); }/*w ww .jav a 2 s . c o m*/ if (filename == null) { throw new IllegalArgumentException("filename most not be null"); } try (BufferedWriter br = Files.newBufferedWriter(filename.toPath(), Charset.forName("UTF-8"), new OpenOption[] { StandardOpenOption.CREATE_NEW })) { // Cleanup empty lines // We do this currently in memory because we don't expect large files anyways while (gCode.lastIndexOf(SEPERATOR + SEPERATOR) != -1) { gCode = gCode.replaceAll(SEPERATOR + SEPERATOR, SEPERATOR); } br.write(gCode.trim()); br.flush(); br.close(); } catch (IOException ex) { System.out.println(ex.getMessage()); } }
From source file:com.romeikat.datamessie.core.base.util.FileUtil.java
public synchronized void appendToFile(final File file, final String content) { final Path path = FileSystems.getDefault().getPath(file.getAbsolutePath()); final Charset charset = Charset.defaultCharset(); try (BufferedWriter writer = Files.newBufferedWriter(path, charset, StandardOpenOption.APPEND)) { writer.write(String.format("%s%n", content)); } catch (final Exception e) { LOG.error("Could not apennd to file " + file.getAbsolutePath(), e); }/*from ww w. ja va 2 s . c o m*/ }
From source file:com.mhs.hboxmaintenanceserver.HBoxMaintenanceServer.java
public void start() { try {/*from ww w. j a v a 2 s . com*/ hbmws = new HBoxMaintenanceWebsocketServer(this, websocket_port); hbmws.start(); hbmws.sendListOfHBoxBy_Interval(); httpServer = HttpServer.createSimpleServer(null, webserver_port); AccessLogBuilder logBuilder = new AccessLogBuilder(DefaultConfig.GRIZZLY_LOG); logBuilder.rotatedDaily().instrument(httpServer.getServerConfiguration()); HBoxMaintenanceServer hbms = this; httpServer.getServerConfiguration().addHttpHandler(new HttpHandler() { private void sendGSON_to_web(OutputStream gos, Gson gson, Object obj) { try (PrintWriter pw = new PrintWriter(gos)) { pw.write(gson.toJson(obj)); pw.close(); } } @Override public void service(Request request, Response response) throws Exception { OutputStream gos = response.getOutputStream(); String uri = request.getRequestURI(); String path = uri.substring(uri.lastIndexOf("/") + 1).trim().toLowerCase(); Gson gson = (new GsonBuilder()).create(); String ip_address, hostname; HBox_Actions hba; Thread thread; Editor editor; switch (path) { case "list_drivers": String[] __paths = new String[0]; File driverFolder = new File(DefaultConfig.DRIVERS_FOLDER); if (driverFolder.exists()) { File[] paths = driverFolder.listFiles((File pathname) -> { String ext = pathname.getAbsolutePath(); ext = ext.substring(ext.lastIndexOf(".") + 1).trim().toLowerCase(); return ext.equals("kar"); }); __paths = new String[paths.length]; int k = 0; for (File _path : paths) { __paths[k] = _path.getName(); k++; } } sendGSON_to_web(gos, gson, __paths); break; case "reboot_hbox": hostname = request.getParameter("hostname"); ip_address = request.getParameter("ip_address"); if (hostname != null && ip_address != null) { hba = new HBox_Actions(ip_address, hostname, hbmws.getConns().toArray(new WebSocket[hbmws.getConns().size()]), new String[] { "hbox_reboot" }, threadGroup_LOG, hbms); thread = new Thread(hba); thread.start(); } break; case "start": String result1 = request.getParameter("result"); String[] drivers = null; if (request.getParameter("drivers") != null) { drivers = (String[]) gson.fromJson(request.getParameter("drivers"), String[].class); } HBox hb = (HBox) gson.fromJson(result1, HBox.class); hosts = hb.getHosts(); actions = hb.getActions(); for (Host host : hosts) { try { HBox_Actions hba1 = new HBox_Actions(host.getIp_address(), host.getHost_name(), hbmws.getConns().toArray(new WebSocket[hbmws.getConns().size()]), actions, threadGroup_LOG, hbms); if (drivers != null) { hba1.setDrivers(drivers); } thread = new Thread(hba1); thread.start(); } catch (Exception ex) { DCXLogger.error(HBoxMaintenanceServer.class, Level.SEVERE, ex); } } break; case "crontab": editor = new Editor(DefaultConfig.HBOX_CRONTAB, FileUtils.readFileToString(new File(DefaultConfig.HBOX_CRONTAB), "UTF-8")); sendGSON_to_web(gos, gson, editor); break; case "wpa_supplicant": editor = new Editor(DefaultConfig.HBOX_WIFI, FileUtils.readFileToString(new File(DefaultConfig.HBOX_WIFI), "UTF-8")); sendGSON_to_web(gos, gson, editor); break; case "apply_changes": String file = request.getParameter("file"); String content = request.getParameter("content"); if (file != null && content != null) { String[] contents; if (content.contains("\r\n")) { contents = content.split("\r\n"); } else if (content.contains("\n\r")) { contents = content.split("\n\r"); } else { contents = content.split("\r"); } if (file.equals("wpa_supplicant.conf") || file.equals("crontab")) { try (BufferedWriter bw = Files.newBufferedWriter( Paths.get(DefaultConfig.HBOX_FOLDER + File.separator + file), Charset.forName("UTF-8"), StandardOpenOption.TRUNCATE_EXISTING)) { for (String s : contents) { bw.write(s); bw.write("\n"); } bw.close(); } } } break; case "logout": request.getSession().removeAttribute("user-login"); try (PrintWriter pw = new PrintWriter(gos)) { pw.write("1"); } break; case "login": String username = request.getParameter("username"); String password = request.getParameter("password"); try (PrintWriter pw = new PrintWriter(gos)) { if (username != null && password != null) { if (saveLoginSession(request.getSession(), username, password)) { pw.write("1"); } else { pw.write("0"); } } else { pw.write("0"); } } break; default: gos.write(getContent(uri, response, request)); } } }); httpServer.start(); } catch (IOException ex) { DCXLogger.error(HBoxMaintenanceServer.class, Level.SEVERE, ex); } }
From source file:com.themodernway.server.core.io.IO.java
public static BufferedWriter toBufferedWriter(final Path path, final OpenOption... options) throws IOException { return Files.newBufferedWriter(CommonOps.requireNonNull(path), UTF_8_CHARSET, options); }
From source file:io.github.swagger2markup.markup.builder.internal.AbstractMarkupDocBuilder.java
/** * 2 newLines are needed at the end of file for file to be included without protection. *///ww w . j a va 2s .c om @Override public void writeToFileWithoutExtension(Path file, Charset charset, OpenOption... options) { try { Files.createDirectories(file.getParent()); } catch (IOException e) { throw new RuntimeException("Failed create directory", e); } try (BufferedWriter writer = Files.newBufferedWriter(file, charset, options)) { writer.write(toString()); writer.write(newLine); writer.write(newLine); } catch (IOException e) { throw new RuntimeException("Failed to write file", e); } if (logger.isInfoEnabled()) { logger.info("Markup document written to: {}", file); } }