List of usage examples for java.nio.file Files write
public static Path write(Path path, Iterable<? extends CharSequence> lines, Charset cs, OpenOption... options) throws IOException
From source file:com.github.jinahya.simple.file.back.LocalFileBackTest.java
@Test(enabled = true, invocationCount = 1) public void read() throws IOException, FileBackException { fileContext.fileOperationSupplier(() -> FileOperation.READ); final ByteBuffer fileKey = randomFileKey(); fileContext.sourceKeySupplier(() -> fileKey); final Path leafPath = LocalFileBack.leafPath(rootPath, fileKey, true); final byte[] fileBytes = randomFileBytes(); final boolean fileWritten = Files.isRegularFile(leafPath) || current().nextBoolean(); if (fileWritten) { Files.write(leafPath, fileBytes, StandardOpenOption.CREATE, StandardOpenOption.WRITE); logger.trace("file written"); }/*from w ww . ja v a 2s.co m*/ fileContext.sourceChannelConsumer(v -> { final byte[] actual = new byte[fileBytes.length]; try { IOUtils.readFully(Channels.newInputStream(v), actual); if (fileWritten) { assertEquals(actual, fileBytes); } } catch (final IOException ioe) { fail("failed to read from source channel", ioe); } }); final ByteArrayOutputStream targetStream = new ByteArrayOutputStream(); fileContext.targetChannelSupplier(() -> { return Channels.newChannel(targetStream); }); fileBack.operate(fileContext); if (fileWritten) { assertEquals(targetStream.toByteArray(), fileBytes); } }
From source file:com.streamsets.datacollector.publicrestapi.CredentialsDeploymentResource.java
private void deployDPMToken(CredentialsBeanJson credentialsBeanJson) throws IOException { LOG.info("Deploying DPM token"); File dpmProperties = new File(runtimeInfo.getConfigDir(), "dpm.properties"); Configuration conf = new Configuration(); Files.write(Paths.get(runtimeInfo.getConfigDir(), "application-token.txt"), credentialsBeanJson.getToken().getBytes(Charsets.UTF_8), CREATE, WRITE); try (FileReader reader = new FileReader(dpmProperties)) { conf.load(reader);/* ww w. ja va 2 s . co m*/ } conf.unset(RemoteSSOService.DPM_BASE_URL_CONFIG); conf.set(RemoteSSOService.DPM_ENABLED, true); conf.set(RemoteSSOService.SECURITY_SERVICE_APP_AUTH_TOKEN_CONFIG, Configuration.FileRef.PREFIX + APPLICATION_TOKEN_TXT + Configuration.FileRef.SUFFIX); conf.set(RemoteSSOService.DPM_DEPLOYMENT_ID, credentialsBeanJson.getDeploymentId()); runtimeInfo.setDeploymentId(credentialsBeanJson.getDeploymentId()); if (!CollectionUtils.isEmpty(credentialsBeanJson.getLabels())) { String labelsString = StringUtils.join(credentialsBeanJson.getLabels().toArray(), ","); LOG.info("SDC will have the following Labels: {}", labelsString); conf.set(RemoteEventHandlerTask.REMOTE_JOB_LABELS, labelsString); } try (FileWriter writer = new FileWriter(dpmProperties)) { conf.save(writer); } Files.write(Paths.get(dpmProperties.getPath()), (RemoteSSOService.DPM_BASE_URL_CONFIG + "=" + credentialsBeanJson.getDpmUrl()).getBytes(), StandardOpenOption.APPEND); runtimeInfo.setDPMEnabled(true); LOG.info("DPM token deployed"); }
From source file:gov.vha.isaac.rf2.filter.RF2Filter.java
@Override public void execute() throws MojoExecutionException { if (!inputDirectory.exists() || !inputDirectory.isDirectory()) { throw new MojoExecutionException("Path doesn't exist or isn't a folder: " + inputDirectory); }//from w w w . ja v a 2s . c o m if (module == null) { throw new MojoExecutionException("You must provide a module or namespace for filtering"); } moduleStrings_.add(module + ""); outputDirectory.mkdirs(); File temp = new File(outputDirectory, inputDirectory.getName()); temp.mkdirs(); Path source = inputDirectory.toPath(); Path target = temp.toPath(); try { getLog().info("Reading from " + inputDirectory.getAbsolutePath()); getLog().info("Writing to " + outputDirectory.getCanonicalPath()); summary_.append("This content was filtered by an RF2 filter tool. The parameters were module: " + module + " software version: " + converterVersion); summary_.append("\r\n\r\n"); getLog().info("Checking for nested child modules"); //look in sct2_Relationship_ files, find anything where the 6th column (destinationId) is the //starting module ID concept - and add that sourceId (5th column) to our list of modules to extract Files.walkFileTree(source, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (file.toFile().getName().startsWith("sct2_Relationship_")) { //don't look for quotes, the data is bad, and has floating instances of '"' all by itself CSVReader csvReader = new CSVReader( new InputStreamReader(new FileInputStream(file.toFile())), '\t', CSVParser.NULL_CHARACTER); String[] line = csvReader.readNext(); if (!line[4].equals("sourceId") || !line[5].equals("destinationId")) { csvReader.close(); throw new IOException("Unexpected error looking for nested modules"); } line = csvReader.readNext(); while (line != null) { if (line[5].equals(moduleStrings_.get(0))) { moduleStrings_.add(line[4]); } line = csvReader.readNext(); } csvReader.close(); } return FileVisitResult.CONTINUE; } }); log("Full module list (including detected nested modules: " + Arrays.toString(moduleStrings_.toArray(new String[moduleStrings_.size()]))); Files.walkFileTree(source, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { Path targetdir = target.resolve(source.relativize(dir)); try { //this just creates the sub-directory in the target Files.copy(dir, targetdir); } catch (FileAlreadyExistsException e) { if (!Files.isDirectory(targetdir)) throw e; } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { handleFile(file, target.resolve(source.relativize(file))); return FileVisitResult.CONTINUE; } }); Files.write(new File(temp, "FilterInfo.txt").toPath(), summary_.toString().getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); } catch (IOException e) { throw new MojoExecutionException("Failure", e); } getLog().info("Filter Complete"); }
From source file:net.dv8tion.jda.core.utils.SimpleLog.java
private static void logToFiles(String msg, Level level) { Set<File> files = collectFiles(level); for (File file : files) { try {/* ww w. java 2s . c om*/ Files.write(file.toPath(), (msg + '\n').getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.APPEND); } catch (IOException e) { e.printStackTrace(); // JDAImpl.LOG.fatal("Could not write log to logFile..."); // JDAImpl.LOG.log(e); } } }
From source file:com.ontotext.s4.service.S4ServiceClientIntegrationTest.java
@Test public void testClassifyFileContentsAsStreamDescClient() throws Exception { ServiceDescriptor temp = ServicesCatalog.getItem("news-classifier"); S4ServiceClient client = new S4ServiceClient(temp, testApiKeyId, testApiKeyPass); serializationFormat = ResponseFormat.JSON; File f = new File("test-file"); try {/*from w ww .ja v a2s.c om*/ Path p = f.toPath(); ArrayList<String> lines = new ArrayList<>(1); lines.add(documentText); Files.write(p, lines, Charset.forName("UTF-8"), StandardOpenOption.CREATE); InputStream result = client.annotateFileContentsAsStream(f, Charset.forName("UTF-8"), SupportedMimeType.PLAINTEXT, serializationFormat); StringWriter writer = new StringWriter(); IOUtils.copy(result, writer, Charset.forName("UTF-8")); assertTrue(writer.toString().contains("category")); assertTrue(writer.toString().contains("allScores")); } finally { f.delete(); } }
From source file:org.deeplearning4j.examples.multigpu.video.VideoGenerator.java
public static void generateVideoData(String outputFolder, String filePrefix, int nVideos, int nFrames, int width, int height, int numShapesPerVideo, boolean backgroundNoise, int numDistractorsPerFrame, long seed) throws Exception { Random r = new Random(seed); for (int i = 0; i < nVideos; i++) { String videoPath = FilenameUtils.concat(outputFolder, filePrefix + "_" + i + ".mp4"); String labelsPath = FilenameUtils.concat(outputFolder, filePrefix + "_" + i + ".txt"); int[] labels = generateVideo(videoPath, nFrames, width, height, numShapesPerVideo, r, backgroundNoise, numDistractorsPerFrame); //Write labels to text file StringBuilder sb = new StringBuilder(); for (int j = 0; j < labels.length; j++) { sb.append(labels[j]);/* w w w.j a v a 2s.co m*/ if (j != labels.length - 1) sb.append("\n"); } Files.write(Paths.get(labelsPath), sb.toString().getBytes("utf-8"), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); } }
From source file:org.fim.internal.hash.FileHasherTest.java
@Test @Ignore//from www . j a v a 2s . co m public void checkHashIsCompleteInEveryCases() throws IOException { if (hashMode != dontHash) { int initialSize = 4190000; Path file = createFileWithSize(initialSize - 1); for (int fileSize = initialSize; fileSize < (10 * _1_MB); fileSize++) { byte contentByte = getContentByte(globalSequenceCount, false); globalSequenceCount++; Files.write(file, new byte[] { contentByte }, CREATE, APPEND); cut.hashFile(file, Files.size(file)); } } }
From source file:net.fatlenny.datacitation.service.GitCitationDBService.java
private void createMasterBranchIfNotExists() throws CitationDBException { try (Git git = new Git(repository)) { String master = Constants.MASTER; ObjectId head = repository.resolve(REF_MASTER); if (head == null) { git.commit().setMessage("Initial commit").call(); String readmeFileName = "README.md"; String[] text = new String[] { "DO NOT DELETE DIRECTORY. USED BY RECITABLE" }; Files.write(Paths.get(getWorkingTreeDir(), readmeFileName), Arrays.asList(text), StandardCharsets.UTF_8, StandardOpenOption.CREATE); git.add().addFilepattern(readmeFileName).call(); PersonIdent personIdent = new PersonIdent("ReCitable", "recitable@fatlenny.net"); git.commit().setMessage("Created README.md").setAuthor(personIdent).setCommitter(personIdent) .call();/*from www. ja v a2 s.c o m*/ } } catch (RevisionSyntaxException | IOException | GitAPIException e) { throw new CitationDBException("Error creating branch master", e); } }
From source file:com.github.jinahya.simple.file.back.LocalFileBackTest.java
@Test(enabled = true, invocationCount = 1) public void write() throws IOException, FileBackException { fileContext.fileOperationSupplier(() -> FileOperation.WRITE); final ByteBuffer fileKey = randomFileKey(); fileContext.targetKeySupplier(() -> fileKey); final Path leafPath = LocalFileBack.leafPath(rootPath, fileKey, true); final byte[] fileBytes = randomFileBytes(); final boolean fileWritten = Files.isRegularFile(leafPath) || current().nextBoolean(); if (fileWritten) { Files.write(leafPath, fileBytes, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE); logger.trace("file written"); }//from w w w .j a v a 2 s .com fileContext.sourceChannelSupplier(() -> Channels.newChannel(new ByteArrayInputStream(fileBytes))); fileContext.targetChannelConsumer(v -> { try { final long copied = IOUtils.copyLarge(new ByteArrayInputStream(fileBytes), Channels.newOutputStream(v)); } catch (final IOException ioe) { logger.error("failed to copy", ioe); } }); fileBack.operate(fileContext); if (fileWritten) { final byte[] actual = Files.readAllBytes(leafPath); assertEquals(actual, fileBytes); } }
From source file:org.apache.nifi.controller.TemplateManager.java
/** * Persists the given template to disk/* w ww .jav a2 s. co m*/ * * @param template template * @throws IOException ioe */ private void persistTemplate(final Template template) throws IOException { final Path path = directory.resolve(template.getDetails().getId() + ".template"); Files.write(path, TemplateSerializer.serialize(template.getDetails()), StandardOpenOption.WRITE, StandardOpenOption.CREATE); }