List of usage examples for java.nio.file StandardOpenOption TRUNCATE_EXISTING
StandardOpenOption TRUNCATE_EXISTING
To view the source code for java.nio.file StandardOpenOption TRUNCATE_EXISTING.
Click Source Link
From source file:com.spectralogic.ds3client.helpers.FileObjectPutter_Test.java
@Test public void testRegularFile() throws IOException { final Path tempDir = Files.createTempDirectory("ds3_file_object_putter_"); final Path tempPath = Files.createTempFile(tempDir, "temp_", ".txt"); try {/* ww w . j av a2 s.c o m*/ try (final SeekableByteChannel channel = Files.newByteChannel(tempPath, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) { channel.write(ByteBuffer.wrap(testData)); } getFileWithPutter(tempDir, tempPath); } finally { Files.deleteIfExists(tempPath); Files.deleteIfExists(tempDir); } }
From source file:org.apache.marmotta.platform.ldp.services.LdpBinaryStoreServiceImpl.java
@Override public boolean store(String resource, InputStream stream) { try {/*from w w w . ja v a 2 s . c om*/ Path file = getFile(resource); Files.createDirectories(file.getParent()); try (OutputStream outputStream = Files.newOutputStream(file, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) { IOUtils.copy(stream, outputStream); } return true; } catch (URISyntaxException | IOException e) { log.error("{} resource cannot be stored on disk: {}", resource, e.getMessage()); return false; } }
From source file:io.gravitee.maven.plugins.json.schema.generator.mojo.Output.java
/** * Create the JSON file associated to the JSON Schema * * @param schema the JSON schema to write into file *//*from w w w . j ava 2s .com*/ private void createJsonFile(JsonSchema schema) { try { ObjectMapper mapper = new ObjectMapper(); String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema); // replace all : with _ this is a reserved character in some file systems Path outputPath = Paths.get( config.getOutputDirectory() + File.separator + schema.getId().replaceAll(":", "_") + ".json"); Files.write(outputPath, json.getBytes(), StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); config.getLogger().info("Created JSON Schema: " + outputPath.normalize().toAbsolutePath().toString()); } catch (JsonProcessingException e) { config.getLogger().warn("Unable to display schema " + schema.getId(), e); } catch (Exception e) { config.getLogger().warn("Unable to write Json file for schema " + schema.getId(), e); } }
From source file:srebrinb.compress.sevenzip.SevenZOutputFile.java
/** * Opens file to write a 7z archive to.//from w w w.java 2 s. com * * @param filename the file to write to * @throws IOException if opening the file fails */ public SevenZOutputFile(final File filename) throws IOException { this(Files.newByteChannel(filename.toPath(), EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING))); }
From source file:divconq.util.IOUtil.java
public static boolean saveEntireFile2(Path dest, String content) { try {/* w ww. j a v a2s . c o m*/ Files.createDirectories(dest.getParent()); Files.write(dest, Utf8Encoder.encode(content), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE, StandardOpenOption.SYNC); } catch (Exception x) { return false; } return true; }
From source file:org.cryptomator.webdav.jackrabbit.EncryptedDir.java
private void addMemberFile(DavResource resource, InputContext inputContext) throws DavException { final Path childPath = ResourcePathUtils.getPhysicalPath(resource); try (final SeekableByteChannel channel = Files.newByteChannel(childPath, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) { cryptor.encryptFile(inputContext.getInputStream(), channel); } catch (SecurityException e) { throw new DavException(DavServletResponse.SC_FORBIDDEN, e); } catch (IOException e) { LOG.error("Failed to create file.", e); throw new IORuntimeException(e); } catch (CounterOverflowException e) { // lets indicate this to the client as a "file too big" error throw new DavException(DavServletResponse.SC_INSUFFICIENT_SPACE_ON_RESOURCE, e); } catch (EncryptFailedException e) { LOG.error("Encryption failed for unknown reasons.", e); throw new IllegalStateException("Encryption failed for unknown reasons.", e); } finally {/*www . j a va2s . c o m*/ IOUtils.closeQuietly(inputContext.getInputStream()); } }
From source file:org.elasticsearch.xpack.security.authc.esnative.tool.SetupPasswordToolIT.java
@SuppressWarnings("unchecked") public void testSetupPasswordToolAutoSetup() throws Exception { final String testConfigDir = System.getProperty("tests.config.dir"); logger.info("--> CONF: {}", testConfigDir); final Path configPath = PathUtils.get(testConfigDir); setSystemPropsForTool(configPath);/*from w w w . ja v a2 s .co m*/ Response nodesResponse = client().performRequest("GET", "/_nodes/http"); Map<String, Object> nodesMap = entityAsMap(nodesResponse); Map<String, Object> nodes = (Map<String, Object>) nodesMap.get("nodes"); Map<String, Object> firstNode = (Map<String, Object>) nodes.entrySet().iterator().next().getValue(); Map<String, Object> firstNodeHttp = (Map<String, Object>) firstNode.get("http"); String nodePublishAddress = (String) firstNodeHttp.get("publish_address"); final int lastColonIndex = nodePublishAddress.lastIndexOf(':'); InetAddress actualPublishAddress = InetAddresses.forString(nodePublishAddress.substring(0, lastColonIndex)); InetAddress expectedPublishAddress = new NetworkService(Collections.emptyList()) .resolvePublishHostAddresses(Strings.EMPTY_ARRAY); final int port = Integer.valueOf(nodePublishAddress.substring(lastColonIndex + 1)); List<String> lines = Files.readAllLines(configPath.resolve("elasticsearch.yml")); lines = lines.stream() .filter(s -> s.startsWith("http.port") == false && s.startsWith("http.publish_port") == false) .collect(Collectors.toList()); lines.add(randomFrom("http.port", "http.publish_port") + ": " + port); if (expectedPublishAddress.equals(actualPublishAddress) == false) { lines.add("http.publish_address: " + InetAddresses.toAddrString(actualPublishAddress)); } Files.write(configPath.resolve("elasticsearch.yml"), lines, StandardCharsets.UTF_8, StandardOpenOption.TRUNCATE_EXISTING); MockTerminal mockTerminal = new MockTerminal(); SetupPasswordTool tool = new SetupPasswordTool(); final int status; if (randomBoolean()) { mockTerminal.addTextInput("y"); // answer yes to continue prompt status = tool.main(new String[] { "auto" }, mockTerminal); } else { status = tool.main(new String[] { "auto", "--batch" }, mockTerminal); } assertEquals(0, status); String output = mockTerminal.getOutput(); logger.info("CLI TOOL OUTPUT:\n{}", output); String[] outputLines = output.split("\\n"); Map<String, String> userPasswordMap = new HashMap<>(); Arrays.asList(outputLines).forEach(line -> { if (line.startsWith("PASSWORD ")) { String[] pieces = line.split(" "); String user = pieces[1]; String password = pieces[pieces.length - 1]; logger.info("user [{}] password [{}]", user, password); userPasswordMap.put(user, password); } }); assertEquals(4, userPasswordMap.size()); userPasswordMap.entrySet().forEach(entry -> { final String basicHeader = "Basic " + Base64.getEncoder() .encodeToString((entry.getKey() + ":" + entry.getValue()).getBytes(StandardCharsets.UTF_8)); try { Response authenticateResponse = client().performRequest("GET", "/_xpack/security/_authenticate", new BasicHeader("Authorization", basicHeader)); assertEquals(200, authenticateResponse.getStatusLine().getStatusCode()); Map<String, Object> userInfoMap = entityAsMap(authenticateResponse); assertEquals(entry.getKey(), userInfoMap.get("username")); } catch (IOException e) { throw new UncheckedIOException(e); } }); }
From source file:com.spectralogic.ds3client.helpers.FileObjectPutter_Test.java
@Test public void testRelativeSymlink() throws IOException, URISyntaxException { assumeFalse(Platform.isWindows());/* w ww.j a v a 2 s .co m*/ final Path tempDir = Files.createTempDirectory("ds3_file_object_rel_test_"); final Path tempPath = Files.createTempFile(tempDir, "temp_", ".txt"); try { try (final SeekableByteChannel channel = Files.newByteChannel(tempPath, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) { channel.write(ByteBuffer.wrap(testData)); } final Path symLinkPath = tempDir.resolve("sym_" + tempPath.getFileName().toString()); final Path relPath = Paths.get("..", getParentDir(tempPath), tempPath.getFileName().toString()); LOG.info("Creating symlink from " + symLinkPath.toString() + " to " + relPath.toString()); Files.createSymbolicLink(symLinkPath, relPath); getFileWithPutter(tempDir, symLinkPath); } finally { Files.deleteIfExists(tempPath); Files.deleteIfExists(tempDir); } }
From source file:divconq.util.IOUtil.java
public static boolean saveEntireFile2(Path dest, Memory content) { try {/*from www.j av a 2 s .c o m*/ Files.createDirectories(dest.getParent()); Files.write(dest, content.toArray(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE, StandardOpenOption.SYNC); } catch (Exception x) { return false; } return true; }