Example usage for java.io File toPath

List of usage examples for java.io File toPath

Introduction

In this page you can find the example usage for java.io File toPath.

Prototype

public Path toPath() 

Source Link

Document

Returns a Path java.nio.file.Path object constructed from this abstract path.

Usage

From source file:ec.util.chart.swing.Charts.java

public static void saveChart(@Nonnull ChartPanel chartPanel) throws IOException {
    JFileChooser fileChooser = new JFileChooser();
    FileFilter defaultFilter = new FileNameExtensionFilter("PNG (.png)", "png");
    fileChooser.addChoosableFileFilter(defaultFilter);
    fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("JPG (.jpg) (.jpeg)", "jpg", "jpeg"));
    if (Charts.canWriteChartAsSVG()) {
        fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("SVG (.svg)", "svg"));
        fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Compressed SVG (.svgz)", "svgz"));
    }/*from  ww w .  j  a va 2  s  . com*/
    fileChooser.setFileFilter(defaultFilter);
    File currentDir = chartPanel.getDefaultDirectoryForSaveAs();
    if (currentDir != null) {
        fileChooser.setCurrentDirectory(currentDir);
    }
    if (fileChooser.showSaveDialog(chartPanel) == JFileChooser.APPROVE_OPTION) {
        File file = fileChooser.getSelectedFile();
        try (OutputStream stream = Files.newOutputStream(file.toPath())) {
            writeChart(getMediaType(file), stream, chartPanel.getChart(), chartPanel.getWidth(),
                    chartPanel.getHeight());
        }
        chartPanel.setDefaultDirectoryForSaveAs(fileChooser.getCurrentDirectory());
    }
}

From source file:edu.wustl.mir.erl.ihe.xdsi.util.DICOMUtility.java

/**
 * Generates a "new" study from an existing study by changing the patient id
 * and the UIDs./*from ww w.java 2  s.  c o  m*/
 * 
 * @param outputFolder complete path to a folder on the file system where the
 * "new" study will be placed. If it does not exist, it will be created. Must
 * have privileges. Everything previously in this directory will be deleted.
 * After the call there will be one file in the directory for each image in
 * the "new" study, with no subdirectories. The image files will be named
 * "999999.dcm", numbered in the order they were processed.
 * 
 * @param inputFolder complete path to a folder on the file system where the
 * study used as a template to build the new study may be found. Must have
 * read privileges. The directory structure under the inputFolder is not
 * relevant, but all files in that structure must be dicom image files which
 * represent the SOPInstances of the study. Nothing in the inputFolder will
 * be modified.
 * 
 * <p><b>Note:</b> Folder names may be given as absolute paths or relative paths, 
 * which will be interpreted in relation to the XDSI root directory.</p>
 * 
 * @param patientIdentifier The patient identifier for the "new" study, in CX
 * format. For example:
 * 
 * <pre>
 *  {@code id-19^^^&1.3.6.1.4.1.21367.2005.3.7&ISO }
 * </pre>
 * 
 * @param studyUID The study Instance UID (0020,000D) for the "new" study.
 * Series and SOPInstance UIDs will be generated by the method.
 * @param accessionNumber The accession number (0008,0050) for the "new"
 * study.
 * @param patientName for example, "Moulton^Fred"
 * @param dateOfBirth for example, 19640523 
 * @param sex for example "M"
 * @param studyDate for example 20141224
 * @throws IOException On any error. TODO Add realistic error handling
 */
public static void reidentifyStudy(String outputFolder, String inputFolder, String patientIdentifier,
        String studyUID, String accessionNumber, String patientName, String dateOfBirth, String sex,
        String studyDate) throws IOException {

    log.info("BO reidentifyStudy");
    outputFolder = Utility.getXDSIRootPath().resolve(outputFolder).toString();
    inputFolder = Utility.getXDSIRootPath().resolve(inputFolder).toString();
    FileUtils.deleteDirectory(new File(outputFolder));
    Files.createDirectories(Paths.get(outputFolder));
    int fileCounter = 0;

    List<File> srcFiles = (List<File>) FileUtils.listFiles(new File(inputFolder), TrueFileFilter.TRUE,
            TrueFileFilter.TRUE);

    DicomInputStream din = null;
    Map<String, String> seriesIds = new HashMap<String, String>();
    if (patientName.equals("")) {
        patientName = "Moulton^Fred";
    }
    if (dateOfBirth.equals(""))
        dateOfBirth = "19910101";
    if (sex.equals(""))
        sex = "M";

    for (File srcFile : srcFiles) {
        try {
            din = new DicomInputStream(srcFile);
            Attributes meta = din.readFileMetaInformation();
            Attributes dataSet = din.readDataset(-1, -1);
            String oldSeriesId = dataSet.getString(Tag.SeriesInstanceUID, "");
            if (seriesIds.containsKey(oldSeriesId) == false) {
                seriesIds.put(oldSeriesId, Identifiers.generateSeriesInstanceUID());
            }
            String newSeriesId = seriesIds.get(oldSeriesId);
            String instanceUID = Identifiers.generateSOPInstanceUID();
            dataSet.setString(Tag.PatientID, VR.LO, patientIdentifier);
            dataSet.setString(Tag.StudyInstanceUID, VR.UI, studyUID);
            dataSet.setString(Tag.SeriesInstanceUID, VR.UI, newSeriesId);
            dataSet.setString(Tag.SOPInstanceUID, VR.UI, instanceUID);
            meta.setString(Tag.MediaStorageSOPInstanceUID, VR.UT, instanceUID);
            dataSet.setString(Tag.AccessionNumber, VR.SH, accessionNumber);
            dataSet.setString(Tag.StudyID, VR.SH, accessionNumber);
            dataSet.setString(Tag.PatientName, VR.PN, patientName);
            dataSet.setString(Tag.Manufacturer, VR.LO, "WUSTL");
            if (!dateOfBirth.equals("")) {
                dataSet.setString(Tag.PatientBirthDate, VR.DA, dateOfBirth);
            }
            if (!sex.equals("")) {
                dataSet.setString(Tag.PatientSex, VR.CS, sex);
            }
            if (!studyDate.equals("")) {
                dataSet.setString(Tag.StudyDate, VR.DA, studyDate);
                dataSet.setString(Tag.SeriesDate, VR.DA, studyDate);
                dataSet.setString(Tag.AcquisitionDate, VR.DA, studyDate);
                dataSet.setString(Tag.ContentDate, VR.DA, studyDate);
                dataSet.setString(Tag.CurveDate, VR.DA, studyDate);
                dataSet.setString(Tag.OverlayDate, VR.DA, studyDate);
                dataSet.setString(Tag.AcquisitionDateTime, VR.DT, studyDate);
            }

            String newFileName = String.format("%06d", fileCounter++) + ".dcm";
            File out = new File(outputFolder, File.separator + newFileName);
            Files.createFile(out.toPath());
            DicomOutputStream dos = new DicomOutputStream(out);
            dos.writeFileMetaInformation(meta);
            dataSet.writeTo(dos);
            dos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    log.info("EO reidentifyStudy");
}

From source file:com.themodernway.server.core.io.IO.java

public static final OutputStream toOutputStream(final File file, final OpenOption... options)
        throws IOException {
    return IO.toOutputStream(file.toPath(), options);
}

From source file:com.depas.utils.FileUtils.java

public static List<File> getAllEntriesInDir(File dir) throws IOException {
    return getAllEntriesInDir(dir.toPath(), p -> true);
}

From source file:co.cask.cdap.etl.tool.UpgradeTool.java

private static void convertFile(String configFilePath, String outputFilePath, ArtifactClient artifactClient)
        throws Exception {
    File configFile = new File(configFilePath);
    if (!configFile.exists()) {
        throw new IllegalArgumentException(configFilePath + " does not exist.");
    }/*  ww  w.j  av a 2s  .c  o m*/
    if (!configFile.isFile()) {
        throw new IllegalArgumentException(configFilePath + " is not a file.");
    }
    String fileContents = new String(Files.readAllBytes(configFile.toPath()), StandardCharsets.UTF_8);

    ETLAppRequest artifactFile = GSON.fromJson(fileContents, ETLAppRequest.class);
    if (!shouldUpgrade(artifactFile.artifact)) {
        throw new IllegalArgumentException("Cannot update for artifact " + artifactFile.artifact + ". "
                + "Please check the artifact is cdap-etl-batch or cdap-etl-realtime in the system scope of version 3.2.x.");
    }

    String version = ETLVersion.getVersion();

    File outputFile = new File(outputFilePath);
    String oldArtifactVersion = artifactFile.artifact.getVersion();
    if (BATCH_NAME.equals(artifactFile.artifact.getName())) {
        ArtifactSummary artifact = new ArtifactSummary(BATCH_NAME, version, ArtifactScope.SYSTEM);
        UpgradeContext upgradeContext = new BatchClientBasedUpgradeContext(Id.Namespace.DEFAULT,
                artifactClient);
        ETLBatchConfig config = convertBatchConfig(oldArtifactVersion, artifactFile.config.toString(),
                upgradeContext);
        AppRequest<ETLBatchConfig> updated = new AppRequest<>(artifact, config);
        try (BufferedWriter writer = Files.newBufferedWriter(outputFile.toPath(), StandardCharsets.UTF_8)) {
            writer.write(GSON.toJson(updated));
        }
    } else {
        ArtifactSummary artifact = new ArtifactSummary(REALTIME_NAME, version, ArtifactScope.SYSTEM);
        UpgradeContext upgradeContext = new RealtimeClientBasedUpgradeContext(Id.Namespace.DEFAULT,
                artifactClient);
        ETLRealtimeConfig config = convertRealtimeConfig(oldArtifactVersion, artifactFile.config.toString(),
                upgradeContext);
        AppRequest<ETLRealtimeConfig> updated = new AppRequest<>(artifact, config);
        try (BufferedWriter writer = Files.newBufferedWriter(outputFile.toPath(), StandardCharsets.UTF_8)) {
            writer.write(GSON.toJson(updated));
        }
    }

    LOG.info("Successfully converted application details from file " + configFilePath + ". "
            + "Results have been written to " + outputFilePath);
}

From source file:com.depas.utils.FileUtils.java

public static List<File> getAllEntriesInDir(File dir, Predicate<File> predicate) throws IOException {
    return getAllEntriesInDir(dir.toPath(), predicate);
}

From source file:org.eclipse.cbi.maven.plugins.macsigner.SignMojo.java

/**
 * Decompresses zip files./* www.j  a  v a 2s. c  o  m*/
 * @param zipFile           The zip file to decompress.
 * @throws IOException
 * @throws MojoExecutionException
 */
private static void unZip(File zipFile, File output_dir) throws IOException, MojoExecutionException {

    ZipArchiveInputStream zis = new ZipArchiveInputStream(new FileInputStream(zipFile));
    ZipArchiveEntry ze;
    String name, parent;
    try {
        ze = zis.getNextZipEntry();
        // check for at least one zip entry
        if (ze == null) {
            throw new MojoExecutionException("Could not decompress " + zipFile);
        }

        while (ze != null) {
            name = ze.getName();

            //make directories
            if (ze.isDirectory()) {
                mkdirs(output_dir, name);
            } else {
                parent = getParentDirAbsolutePath(name);
                mkdirs(output_dir, parent);

                File outFile = new File(output_dir, name);
                outFile.createNewFile();

                // check for match in executable list
                if (executableFiles.contains(name)) {
                    Files.setPosixFilePermissions(outFile.toPath(),
                            PosixFilePermissions.fromString("rwxr-x---"));
                }

                FileOutputStream fos = new FileOutputStream(outFile);

                copyInputStreamToOutputStream(zis, fos);
                fos.close();
            }
            ze = zis.getNextZipEntry();
        }
    } finally {
        zis.close();
    }
}

From source file:at.tugraz.sss.serv.SSFileU.java

private static void formatAudioAndVideoFileName(final File file) throws Exception {

    final Path pathToFile = file.toPath();
    String fileName = pathToFile.getFileName().toString().toLowerCase();
    final SSFileExtE fileExt = SSFileExtE.ext(fileName);

    if (!SSFileExtE.isAudioOrVideoFileExt(fileExt)) {
        return;//from w  ww .  j  a v  a2s.  c om
    }

    fileName = SSStrU.replaceAllBlanksSpecialCharactersDoubleDots(fileName, SSStrU.underline);

    try {
        Files.move(pathToFile, pathToFile.resolveSibling(fileName));
    } catch (FileAlreadyExistsException error) {
        System.out.println("file " + pathToFile.resolveSibling(fileName) + " already exists!");
    }
}

From source file:co.cask.cdap.etl.tool.UpgradeTool.java

private static ClientConfig getClientConfig(CommandLine commandLine) throws IOException {
    String uriStr = commandLine.hasOption("u") ? commandLine.getOptionValue("u") : "localhost:10000";
    if (!uriStr.contains("://")) {
        uriStr = "http://" + uriStr;
    }/* ww  w.  j  ava  2s  .c o  m*/
    URI uri = URI.create(uriStr);
    String hostname = uri.getHost();
    int port = uri.getPort();
    boolean sslEnabled = "https".equals(uri.getScheme());
    ConnectionConfig connectionConfig = ConnectionConfig.builder().setHostname(hostname).setPort(port)
            .setSSLEnabled(sslEnabled).build();

    int readTimeout = commandLine.hasOption("t") ? Integer.parseInt(commandLine.getOptionValue("t"))
            : DEFAULT_READ_TIMEOUT_MILLIS;
    ClientConfig.Builder clientConfigBuilder = ClientConfig.builder().setDefaultReadTimeout(readTimeout)
            .setConnectionConfig(connectionConfig);

    if (commandLine.hasOption("a")) {
        String tokenFilePath = commandLine.getOptionValue("a");
        File tokenFile = new File(tokenFilePath);
        if (!tokenFile.exists()) {
            throw new IllegalArgumentException("Access token file " + tokenFilePath + " does not exist.");
        }
        if (!tokenFile.isFile()) {
            throw new IllegalArgumentException("Access token file " + tokenFilePath + " is not a file.");
        }
        String tokenValue = new String(Files.readAllBytes(tokenFile.toPath()), StandardCharsets.UTF_8).trim();
        AccessToken accessToken = new AccessToken(tokenValue, 82000L, "Bearer");
        clientConfigBuilder.setAccessToken(accessToken);
    }

    return clientConfigBuilder.build();
}

From source file:com.ejisto.util.IOUtils.java

public static void zipDirectory(File src, String outputFilePath) throws IOException {
    Path out = Paths.get(outputFilePath);
    if (Files.exists(out)) {
        Files.delete(out);/*  w  w  w  .  j av a2 s  .com*/
    }
    String filePath = out.toUri().getPath();
    Map<String, String> env = new HashMap<>();
    env.put("create", "true");
    try (FileSystem targetFs = FileSystems.newFileSystem(URI.create("jar:file:" + filePath), env)) {
        Files.walkFileTree(src.toPath(), new CopyFileVisitor(src.toPath(), targetFs.getPath("/")));
    }
}