Example usage for java.nio.file FileSystems getDefault

List of usage examples for java.nio.file FileSystems getDefault

Introduction

In this page you can find the example usage for java.nio.file FileSystems getDefault.

Prototype

public static FileSystem getDefault() 

Source Link

Document

Returns the default FileSystem .

Usage

From source file:com.team3637.service.TeamServiceMySQLImpl.java

@Override
public void importCSV(String inputFile) {
    try {/*w  w w.j  a va  2s  . c o m*/
        String csvData = new String(Files.readAllBytes(FileSystems.getDefault().getPath(inputFile)));
        csvData = csvData.replaceAll("\\r", "");
        CSVParser parser = CSVParser.parse(csvData, CSVFormat.DEFAULT.withRecordSeparator("\n"));
        for (CSVRecord record : parser) {
            Team team = new Team();
            team.setId(Integer.parseInt(record.get(0)));
            team.setTeam(Integer.parseInt(record.get(1)));
            team.setAvgscore(Double.parseDouble(record.get(2)));
            team.setMatches(Integer.parseInt(record.get(3)));
            String[] tags = record.get(4).substring(1, record.get(4).length() - 1).split(",");
            for (int i = 0; i < tags.length; i++)
                tags[i] = tags[i].trim();
            if (tags.length > 0 && !tags[0].equals(""))
                team.setTags(Arrays.asList(tags));
            else
                team.setTags(new ArrayList<String>());
            if (checkForTeam(team.getTeam()))
                update(team);
            else
                create(team);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.liferay.sync.engine.service.persistence.SyncFilePersistence.java

public void renameByParentFilePathName(final String sourceParentFilePathName,
        final String targetParentFilePathName) throws SQLException {

    Callable<Object> callable = new Callable<Object>() {

        @Override/*w  w w . jav a  2  s.c o  m*/
        public Object call() throws Exception {
            FileSystem fileSystem = FileSystems.getDefault();

            List<SyncFile> syncFiles = findByParentFilePathName(sourceParentFilePathName);

            for (SyncFile syncFile : syncFiles) {
                String filePathName = syncFile.getFilePathName();

                filePathName = StringUtils.replaceOnce(filePathName,
                        sourceParentFilePathName + fileSystem.getSeparator(),
                        targetParentFilePathName + fileSystem.getSeparator());

                syncFile.setFilePathName(filePathName);

                update(syncFile);
            }

            return null;
        }

    };

    callBatchTasks(callable);
}

From source file:com.liferay.sync.engine.SyncSystemTest.java

protected void addFolder(Path testFilePath, JsonNode stepJsonNode) throws Exception {

    SyncSite syncSite = getSyncSite(stepJsonNode);

    String dependency = getString(stepJsonNode, "dependency");

    final Path dependencyFilePath = getDependencyFilePath(testFilePath, dependency);

    FileSystem fileSystem = FileSystems.getDefault();

    final Path targetFilePath = Paths.get(FileUtil.getFilePathName(syncSite.getFilePathName(),
            dependency.replace("common" + fileSystem.getSeparator(), "")));

    Files.walkFileTree(dependencyFilePath, new SimpleFileVisitor<Path>() {

        @Override/*from  w ww .j a  va 2 s .  co m*/
        public FileVisitResult preVisitDirectory(Path filePath, BasicFileAttributes basicFileAttributes)
                throws IOException {

            Path relativeFilePath = dependencyFilePath.relativize(filePath);

            Files.createDirectories(targetFilePath.resolve(relativeFilePath));

            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Path filePath, BasicFileAttributes basicFileAttributes)
                throws IOException {

            Path relativeFilePath = dependencyFilePath.relativize(filePath);

            Files.copy(filePath, targetFilePath.resolve(relativeFilePath));

            return FileVisitResult.CONTINUE;
        }

    });
}

From source file:edu.vt.vbi.patric.cache.DataLandingGenerator.java

public boolean createCacheFileProteinFamilies(String filePath) {
    boolean isSuccess = false;
    JSONObject jsonData = new JSONObject();
    JSONObject data;/* w  w  w .ja v a  2 s.  c  om*/

    // from WP
    // data
    data = read(baseURL + "/tab/dlp-proteinfamilies-data/?req=passphrase");
    if (data != null) {
        jsonData.put("data", data);
    }
    // tools
    data = read(baseURL + "/tab/dlp-proteinfamilies-tools/?req=passphrase");
    if (data != null) {
        jsonData.put("tools", data);
    }
    // process
    data = read(baseURL + "/tab/dlp-proteinfamilies-process/?req=passphrase");
    if (data != null) {
        jsonData.put("process", data);
    }
    // download
    data = read(baseURL + "/tab/dlp-proteinfamilies-download/?req=passphrase");
    if (data != null) {
        jsonData.put("download", data);
    }
    //
    // add popularGenra
    data = getPopularGeneraFigfam();
    if (data != null) {
        jsonData.put("popularGenomes", data);
    }
    // add figfam graph data
    data = getProteinFamilies();
    if (data != null) {
        jsonData.put("FIGfams", data);
    }

    // save jsonData to file
    try (PrintWriter jsonOut = new PrintWriter(
            Files.newBufferedWriter(FileSystems.getDefault().getPath(filePath), Charset.defaultCharset()));) {
        jsonData.writeJSONString(jsonOut);
        isSuccess = true;
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }
    return isSuccess;
}

From source file:rescustomerservices.GmailQuickstart.java

/**
 * Create a MimeMessage using the parameters provided.
 *
 * @param to Email address of the receiver.
 * @param from Email address of the sender, the mailbox account.
 * @param subject Subject of the email./* w w  w  .j  av a2s  .  c om*/
 * @param bodyText Body text of the email.
 * @param fileDir Path to the directory containing attachment.
 * @param filename Name of file to be attached.
 * @return MimeMessage to be used to send email.
 * @throws MessagingException
 */
public MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText,
        String fileDir, String filename) throws MessagingException, IOException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);
    InternetAddress tAddress = new InternetAddress(to);
    InternetAddress fAddress = new InternetAddress(from);

    email.setFrom(fAddress);
    email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
    email.setSubject(subject);

    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent(bodyText, "text/plain");
    mimeBodyPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\"");

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(mimeBodyPart);

    mimeBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(fileDir + filename);

    mimeBodyPart.setDataHandler(new DataHandler(source));
    mimeBodyPart.setFileName(filename);
    String contentType = Files.probeContentType(FileSystems.getDefault().getPath(fileDir, filename));
    mimeBodyPart.setHeader("Content-Type", contentType + "; name=\"" + filename + "\"");
    mimeBodyPart.setHeader("Content-Transfer-Encoding", "base64");

    multipart.addBodyPart(mimeBodyPart);

    email.setContent(multipart);

    return email;
}

From source file:cpd3314.project.CPD3314ProjectTest.java

@Test
public void testSortDAndLimitAndOutput() throws Exception {
    System.out.println("main");
    String[] args = { "-sort=D", "-o=d", "-limit=10" };
    CPD3314Project.main(args);/*from www  .j a v a2s . c o m*/
    File expected = FileSystems.getDefault().getPath("testFiles", "sortD.xml").toFile();
    File result = new File("d.xml");
    assertTrue("Output File Doesn't Exist", result.exists());
    assertXMLFilesEqual(expected, result);
}

From source file:org.wikidata.wdtk.testing.MockDirectoryManager.java

@Override
public List<String> getSubdirectories(String glob) throws IOException {
    List<String> result = new ArrayList<String>();
    PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + glob);
    for (Path path : files.keySet()) {
        if (!this.directory.equals(path.getParent())) {
            continue;
        }//from  w w  w .ja  va2 s  .c om
        if (pathMatcher.matches(path.getFileName())) {
            result.add(path.getFileName().toString());
        }
    }
    return result;
}

From source file:org.evosuite.junit.CoverageAnalysisWithRefectionSystemTest.java

@Test
public void testBindFilteredEventsToMethod() throws IOException {

    EvoSuite evosuite = new EvoSuite();

    String targetClass = ClassPublicInterface.class.getCanonicalName();
    String testClass = ClassPublicInterfaceTest.class.getCanonicalName();
    Properties.TARGET_CLASS = targetClass;

    Properties.CRITERION = new Properties.Criterion[] { Properties.Criterion.LINE };

    Properties.OUTPUT_VARIABLES = RuntimeVariable.Total_Goals + "," + RuntimeVariable.LineCoverage;
    Properties.STATISTICS_BACKEND = StatisticsBackend.CSV;
    Properties.COVERAGE_MATRIX = true;

    String[] command = new String[] { "-class", targetClass, "-Djunit=" + testClass, "-measureCoverage" };

    SearchStatistics statistics = (SearchStatistics) evosuite.parseCommandLine(command);
    Assert.assertNotNull(statistics);// w ww  .j a  v  a 2 s. c  o  m

    Map<String, OutputVariable<?>> outputVariables = statistics.getOutputVariables();

    // The number of lines seems to be different depending on the compiler
    assertTrue(27 - ((Integer) outputVariables.get(RuntimeVariable.Total_Goals.name()).getValue()) <= 1);
    assertTrue(11 - ((Integer) outputVariables.get(RuntimeVariable.Covered_Goals.name()).getValue()) <= 1);
    assertEquals(1, (Integer) outputVariables.get(RuntimeVariable.Tests_Executed.name()).getValue(), 0.0);

    // Assert that all test cases have passed

    String matrix_file = System.getProperty("user.dir") + File.separator + Properties.REPORT_DIR
            + File.separator + "data" + File.separator + targetClass + File.separator
            + Properties.Criterion.LINE.name() + File.separator + Properties.COVERAGE_MATRIX_FILENAME;
    System.out.println("matrix_file: " + matrix_file);

    List<String> lines = Files.readAllLines(FileSystems.getDefault().getPath(matrix_file));
    assertTrue(lines.size() == 1);
    assertTrue(lines.get(0).replace(" ", "").endsWith("+"));
}

From source file:business.services.FileService.java

public File clone(File file) {
    try {/*from   www.  j  ava  2  s  . com*/
        FileSystem fileSystem = FileSystems.getDefault();
        // source
        Path source = fileSystem.getPath(uploadPath, file.getFilename());
        // target
        Path path = fileSystem.getPath(uploadPath).normalize();
        String prefix = getBasename(file.getFilename());
        String suffix = getExtension(file.getFilename());
        Path target = Files.createTempFile(path, prefix, suffix).normalize();
        // copy
        log.info("Copying " + source + " to " + target + " ...");
        Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
        // save clone
        File result = file.clone();
        result.setFilename(target.getFileName().toString());
        return save(result);
    } catch (IOException e) {
        log.error(e);
        throw new FileCopyError();
    }
}

From source file:cpd3314.project.CPD3314ProjectTest.java

@Test
public void testGetIDAndOutput() throws Exception {
    System.out.println("main");
    String[] args = { "-getID=400", "-o=fourHundred" };
    CPD3314Project.main(args);//from   ww w  . j  a  va  2s. co  m
    File expected = FileSystems.getDefault().getPath("testFiles", "get400.xml").toFile();
    File result = new File("fourHundred.xml");
    assertTrue("Output File Doesn't Exist", result.exists());
    assertXMLFilesEqual(expected, result);
}