Example usage for java.nio.file StandardOpenOption CREATE

List of usage examples for java.nio.file StandardOpenOption CREATE

Introduction

In this page you can find the example usage for java.nio.file StandardOpenOption CREATE.

Prototype

StandardOpenOption CREATE

To view the source code for java.nio.file StandardOpenOption CREATE.

Click Source Link

Document

Create a new file if it does not exist.

Usage

From source file:org.tinywind.springi18nconverter.converter.ExcelConverter.java

@Override
@SuppressWarnings("unchecked")
public void decode(File sourceFile, String targetDir, String targetEncoding, Boolean describeByNative) {
    final String sourceFileName = sourceFile.getName().toLowerCase();
    if (Arrays.stream(JS_POSTFIX_ARRAY).filter(
            postfix -> sourceFileName.lastIndexOf(postfix) == sourceFileName.length() - postfix.length())
            .count() == 0)//from w  w  w .  j av a2s.c o  m
        return;

    try {
        final Map<String, List<String>> stringListMap = new HashMap<>();
        final FileInputStream file = new FileInputStream(sourceFile);
        Iterator<Row> rowIterator;
        try {
            final XSSFWorkbook workbook = new XSSFWorkbook(file);
            final XSSFSheet sheet = workbook.getSheetAt(0);
            rowIterator = sheet.iterator();
        } catch (OfficeXmlFileException e) {
            System.err.println(" exception:" + e.getMessage());
            final HSSFWorkbook workbook = new HSSFWorkbook(file);
            final HSSFSheet sheet = workbook.getSheetAt(0);
            rowIterator = sheet.iterator();
        }

        while (rowIterator.hasNext()) {
            final Row row = rowIterator.next();
            final String key = row.getCell(COLUMN_KEY).getStringCellValue();
            final String language = row.getCell(COLUMN_LANG).getStringCellValue();
            final String value = row.getCell(COLUMN_VALUE).getStringCellValue().trim();
            if (StringUtils.isEmpty(key) || StringUtils.isEmpty(language) || StringUtils.isEmpty(value))
                continue;

            List<String> stringList = stringListMap.get(language);
            if (stringList == null) {
                stringList = new ArrayList<>();
                stringListMap.put(language, stringList);
            }

            final String newLine = "\\\n";
            String lastValue = "", token;
            final BufferedReader reader = new BufferedReader(new StringReader(value));
            while ((token = reader.readLine()) != null)
                lastValue += token + newLine;
            reader.close();
            if (lastValue.lastIndexOf(newLine) == lastValue.length() - newLine.length())
                lastValue = lastValue.substring(0, lastValue.length() - newLine.length());

            addProperty(stringList, key, lastValue, describeByNative);
        }

        for (String language : stringListMap.keySet()) {
            Files.write(Paths.get(new File(targetDir, messagesPropertiesFileName(language)).toURI()),
                    stringListMap.get(language), Charset.forName(targetEncoding), StandardOpenOption.CREATE,
                    StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);
        }
    } catch (Exception e) {
        System.err.println(" FAIL to convert: " + sourceFile.getAbsolutePath());
        e.printStackTrace();
    }
}

From source file:com.codealot.textstore.FileStore.java

@Override
public String storeText(final Reader reader) throws IOException {
    Objects.requireNonNull(reader, "No reader provided");

    // make the digester
    final MessageDigest digester = getDigester();

    // make temp file
    final Path textPath = Paths.get(this.storeRoot, UUID.randomUUID().toString());

    // stream to file, building digest
    final ReaderInputStream readerAsBytes = new ReaderInputStream(reader, StandardCharsets.UTF_8);
    try {//  www .j a  v a  2  s.co  m
        final byte[] bytes = new byte[1024];
        int readLength = 0;
        long totalRead = 0L;

        while ((readLength = readerAsBytes.read(bytes)) > 0) {
            totalRead += readLength;

            digester.update(bytes, 0, readLength);

            final byte[] readBytes = Arrays.copyOf(bytes, readLength);
            Files.write(textPath, readBytes, StandardOpenOption.CREATE, StandardOpenOption.WRITE,
                    StandardOpenOption.APPEND);
        }
        // check that something was read
        if (totalRead == 0L) {
            return this.storeText("");
        }
        // make the hash
        final String hash = byteToHex(digester.digest());

        // store the text, if new
        final Path finalPath = Paths.get(this.storeRoot, hash);
        if (Files.exists(finalPath)) {
            // already existed, so delete uuid named one
            Files.deleteIfExists(textPath);
        } else {
            // rename the file
            Files.move(textPath, finalPath);
        }
        return hash;
    } finally {
        if (readerAsBytes != null) {
            readerAsBytes.close();
        }
    }
}

From source file:org.basinmc.maven.plugins.minecraft.AbstractArtifactMojo.java

/**
 * Fetches any resources from a remote HTTP server and stores it in a specified file.
 *//*  w w w  .j a v a 2  s. c  om*/
protected void fetch(@Nonnull URI uri, @Nonnull Path target) throws IOException {
    this.fetch(uri, FileChannel.open(target, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING,
            StandardOpenOption.WRITE));
}

From source file:org.darkware.wpman.security.ChecksumDatabase.java

/**
 * Write the database to the attached file path. This path is declared in the constructor and cannot be
 * changed./*  www .  j  a  v a2 s  . c  o m*/
 */
public void writeDatabase() {
    this.lock.writeLock().lock();
    try {
        ChecksumDatabase.log.info("Writing integrity database: {}", this.dbFile);
        try (BufferedWriter db = Files.newBufferedWriter(this.dbFile, StandardCharsets.UTF_8,
                StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) {
            for (Map.Entry<Path, String> entry : this.hashes.entrySet()) {
                db.write(entry.getKey().toString());
                db.write(":");
                db.write(entry.getValue());
                db.newLine();
            }
        } catch (IOException e) {
            ChecksumDatabase.log.error("Error while writing integrity database: {}", e.getLocalizedMessage(),
                    e);
        }
    } finally {
        this.lock.writeLock().unlock();
    }
}

From source file:org.cyclop.service.common.FileStorage.java

private FileChannel openForWrite(Path histPath) throws IOException {
    FileChannel byteChannel = FileChannel.open(histPath, StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);
    byteChannel.force(true);/* w w w . j a v a2 s.  com*/
    FileChannel lockChannel = lock(histPath, byteChannel);
    return lockChannel;
}

From source file:org.bonitasoft.web.designer.workspace.WorkspaceTest.java

@Test
public void should_not_copy_widget_file_if_it_is_already_in_widget_repository_folder() throws Exception {
    mockWidgetsBasePath(temporaryFolder.toPath().resolve("widgets"));

    //We create the widget files
    Path labelDir = temporaryFolder.newFolderPath("widgets", "pbLabel");
    Path labelFile = labelDir.resolve("pbLabel.json");
    byte[] fileContent = "{\"id\":\"pbLabel\", \"template\": \"<div>Hello</div>\"}"
            .getBytes(StandardCharsets.UTF_8);
    write(labelFile, fileContent, StandardOpenOption.CREATE);

    workspace.initialize();//from www . ja v  a2s . c  o m

    assertThat(readAllBytes(labelFile)).isEqualTo(fileContent);
    assertThat(pathResolver.getWidgetsRepositoryPath().resolve("pbLabel/pbLabel.json")).exists();
}

From source file:org.epics.archiverappliance.etl.ZeroByteFilesTest.java

public void testZeroByteFilesInSource() throws Exception {
    // Create zero byte files in the ETL source; since this is a daily partition, we need something like so sine:2016_03_31.pb
    String pvName = ConfigServiceForTests.ARCH_UNIT_TEST_PVNAME_PREFIX + "ETL_testZeroSrc";
    VoidFunction zeroByteGenerator = () -> {
        for (int day = 2; day < 10; day++) {
            Path zeroSrcPath = Paths.get(etlSrc.getRootFolder(),
                    pvNameToKeyConverter.convertPVNameToKey(pvName)
                            + TimeUtils.getPartitionName(TimeUtils.getCurrentEpochSeconds() - day * 86400,
                                    PartitionGranularity.PARTITION_DAY)
                            + PlainPBStoragePlugin.PB_EXTENSION);
            logger.info("Creating zero byte file " + zeroSrcPath);
            Files.write(zeroSrcPath, new byte[0], StandardOpenOption.CREATE);
        }// w w w .ja  v  a2s .co  m
    };
    runETLAndValidate(pvName, zeroByteGenerator);
}

From source file:com.github.jinahya.simple.file.back.LocalFileBackTest.java

@Test(enabled = true, invocationCount = 1)
public void delete() throws IOException, FileBackException {

    fileContext.fileOperationSupplier(() -> FileOperation.DELETE);

    final ByteBuffer fileKey = randomFileKey();
    if (current().nextBoolean()) {
        fileContext.sourceKeySupplier(() -> fileKey);
    } else {/*from w ww . j ava 2 s  . c o  m*/
        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, StandardOpenOption.WRITE);
        logger.trace("file written");
    }

    fileBack.operate(fileContext);
}

From source file:business.services.FileService.java

public File uploadPart(User user, String name, File.AttachmentType type, MultipartFile file, Integer chunk,
        Integer chunks, String flowIdentifier) {
    try {/*from   w  ww  . j  a  va  2s  .  co m*/
        String identifier = user.getId().toString() + "_" + flowIdentifier;
        String contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        log.info("File content-type: " + file.getContentType());
        try {
            contentType = MediaType.valueOf(file.getContentType()).toString();
            log.info("Media type: " + contentType);
        } catch (InvalidMediaTypeException e) {
            log.warn("Invalid content type: " + e.getMediaType());
            //throw new FileUploadError("Invalid content type: " + e.getMediaType());
        }
        InputStream input = file.getInputStream();

        // Create temporary file for chunk
        Path path = fileSystem.getPath(uploadPath).normalize();
        if (!path.toFile().exists()) {
            Files.createDirectory(path);
        }
        name = URLEncoder.encode(name, "utf-8");

        String prefix = getBasename(name);
        String suffix = getExtension(name);
        Path f = Files.createTempFile(path, prefix, suffix + "." + chunk + ".chunk").normalize();
        // filter path names that point to places outside the upload path.
        // E.g., to prevent that in cases where clients use '../' in the filename
        // arbitrary locations are reachable.
        if (!Files.isSameFile(path, f.getParent())) {
            // Path f is not in the upload path. Maybe 'name' contains '..'?
            throw new FileUploadError("Invalid file name");
        }
        log.info("Copying file to " + f.toString());

        // Copy chunk to temporary file
        Files.copy(input, f, StandardCopyOption.REPLACE_EXISTING);

        // Save chunk location in chunk map
        SortedMap<Integer, Path> chunkMap;
        synchronized (uploadChunks) {
            // FIXME: perhaps use a better identifier? Not sure if this one 
            // is unique enough...
            chunkMap = uploadChunks.get(identifier);
            if (chunkMap == null) {
                chunkMap = new TreeMap<Integer, Path>();
                uploadChunks.put(identifier, chunkMap);
            }
        }
        chunkMap.put(chunk, f);
        log.info("Chunk " + chunk + " saved to " + f.toString());

        // Assemble complete file if all chunks have been received
        if (chunkMap.size() == chunks.intValue()) {
            uploadChunks.remove(identifier);
            Path assembly = Files.createTempFile(path, prefix, suffix).normalize();
            // filter path names that point to places outside the upload path.
            // E.g., to prevent that in cases where clients use '../' in the filename
            // arbitrary locations are reachable.
            if (!Files.isSameFile(path, assembly.getParent())) {
                // Path assembly is not in the upload path. Maybe 'name' contains '..'?
                throw new FileUploadError("Invalid file name");
            }
            log.info("Assembling file " + assembly.toString() + " from " + chunks + " chunks...");
            OutputStream out = Files.newOutputStream(assembly, StandardOpenOption.CREATE,
                    StandardOpenOption.APPEND);

            // Copy chunks to assembly file, delete chunk files
            for (int i = 1; i <= chunks; i++) {
                //log.info("Copying chunk " + i + "...");
                Path source = chunkMap.get(new Integer(i));
                if (source == null) {
                    log.error("Cannot find chunk " + i);
                    throw new FileUploadError("Cannot find chunk " + i);
                }
                Files.copy(source, out);
                Files.delete(source);
            }

            // Save assembled file name to database
            log.info("Saving attachment to database...");
            File attachment = new File();
            attachment.setName(URLDecoder.decode(name, "utf-8"));
            attachment.setType(type);
            attachment.setMimeType(contentType);
            attachment.setDate(new Date());
            attachment.setUploader(user);
            attachment.setFilename(assembly.getFileName().toString());
            attachment = fileRepository.save(attachment);
            return attachment;
        }
        return null;
    } catch (IOException e) {
        log.error(e);
        throw new FileUploadError(e.getMessage());
    }
}

From source file:org.linagora.linshare.webservice.uploadrequest.impl.FlowUploaderRestServiceImpl.java

@Path("/")
@POST/*from w w w . jav a2s  . c  o  m*/
@Consumes("multipart/form-data")
@Override
public Response uploadChunk(@Multipart(CHUNK_NUMBER) long chunkNumber,
        @Multipart(TOTAL_CHUNKS) long totalChunks, @Multipart(CHUNK_SIZE) long chunkSize,
        @Multipart(TOTAL_SIZE) long totalSize, @Multipart(IDENTIFIER) String identifier,
        @Multipart(FILENAME) String filename, @Multipart(RELATIVE_PATH) String relativePath,
        @Multipart(FILE) InputStream file, MultipartBody body,
        @Multipart(REQUEST_URL_UUID) String uploadRequestUrlUuid, @Multipart(PASSWORD) String password)
        throws BusinessException {

    logger.debug("upload chunk number : " + chunkNumber);
    identifier = cleanIdentifier(identifier);
    Validate.isTrue(isValid(chunkNumber, chunkSize, totalSize, identifier, filename));
    try {
        logger.debug("writing chunk number : " + chunkNumber);
        java.nio.file.Path tempFile = getTempFile(identifier);
        FileChannel fc = FileChannel.open(tempFile, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        byte[] byteArray = IOUtils.toByteArray(file);
        fc.write(ByteBuffer.wrap(byteArray), (chunkNumber - 1) * chunkSize);
        fc.close();
        chunkedFiles.get(identifier).addChunk(chunkNumber);
        if (isUploadFinished(identifier, chunkSize, totalSize)) {
            logger.debug("upload finished ");
            InputStream inputStream = Files.newInputStream(tempFile, StandardOpenOption.READ);
            File tempFile2 = getTempFile(inputStream, "rest-flowuploader", filename);
            try {
                uploadRequestUrlFacade.addUploadRequestEntry(uploadRequestUrlUuid, password, tempFile2,
                        filename);
            } finally {
                deleteTempFile(tempFile2);
            }
            ChunkedFile remove = chunkedFiles.remove(identifier);
            Files.deleteIfExists(remove.getPath());
            return Response.ok("upload success").build();
        } else {
            logger.debug("upload pending ");
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return Response.ok("upload success").build();
}