Example usage for java.io File separatorChar

List of usage examples for java.io File separatorChar

Introduction

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

Prototype

char separatorChar

To view the source code for java.io File separatorChar.

Click Source Link

Document

The system-dependent default name-separator character.

Usage

From source file:de.andreasschoknecht.LS3.DocumentCollection.java

/**
 * Creates the LS3Documents of this document collection. Each document contains the relevant information of a PNML file for the LS3.
 *///  w w  w.  j ava 2 s  .  c o m
public void createDocuments() {
    for (int i = 0; i < fileList.length; i++) {
        ls3Documents.add(new LS3Document(pnmlPath + File.separatorChar + fileList[i]));
    }
    PNMLReader pnmlReader = new PNMLReader();
    try {
        pnmlReader.processDocuments(this);
    } catch (JDOMException | IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.foilen.smalltools.spring.messagesource.UsageMonitoringMessageSource.java

private void init() {

    // Check the base folder
    File basenameFile = new File(basename);
    logger.info("Base name is {}", basename);
    File directory = basenameFile.getParentFile();
    logger.info("Base directory is {}", directory.getAbsoluteFile());
    if (!directory.exists()) {
        throw new SmallToolsException("Directory: " + directory.getAbsolutePath() + " does not exists");
    }//from w  ww .  j ava  2s  .  c om

    tmpUsed = new File(directory.getAbsolutePath() + File.separatorChar + "_messages_usage.txt");

    // Check the files in it
    String startswith = basenameFile.getName() + "_";
    String endswith = ".properties";
    for (File file : directory.listFiles(
            (FilenameFilter) (dir, name) -> name.startsWith(startswith) && name.endsWith(endswith))) {
        // Create the locale
        logger.info("Found messages file {}", directory.getAbsoluteFile());
        String filename = file.getName();
        String localePart = filename.substring(startswith.length(), filename.length() - endswith.length());
        Locale locale = new Locale(localePart);
        logger.info("Locale is {} -> {}", localePart, locale);
        filePerLocale.put(locale, file);

        // Load the file
        Properties properties = new Properties();
        try (FileInputStream inputStream = new FileInputStream(file)) {
            properties.load(new InputStreamReader(inputStream, CharsetTools.UTF_8));
        } catch (IOException e) {
            logger.error("Problem reading the property file {}", file.getAbsoluteFile(), e);
            throw new SmallToolsException("Problem reading the file", e);
        }

        // Check codes and save values
        Map<String, String> messages = new HashMap<>();
        messagesPerLocale.put(locale, messages);
        for (Object key : properties.keySet()) {
            String name = (String) key;
            String value = properties.getProperty(name);
            allCodesInFiles.add(name);
            messages.put(name, value);
        }

    }

    // Add missing codes in all the maps (copy one that has it)
    for (Locale locale : filePerLocale.keySet()) {
        Set<String> missingCodes = new HashSet<>();
        Map<String, String> messagesForCurrentLocale = messagesPerLocale.get(locale);

        // Get the ones missing
        missingCodes.addAll(allCodesInFiles);
        missingCodes.removeAll(messagesForCurrentLocale.keySet());

        for (String missingCode : missingCodes) {
            logger.info("Locale {} was missing code {}", locale, missingCode);

            String codeValue = findAnyValue(missingCode);
            messagesForCurrentLocale.put(missingCode, codeValue);
        }
    }

    // Load the already known codes
    if (tmpUsed.exists()) {
        for (String line : FileTools.readFileLinesIteration(tmpUsed.getAbsolutePath())) {
            knownUsedCodes.add(line);
        }
    }

    smoothTrigger = new SmoothTrigger(() -> {

        synchronized (lock) {

            logger.info("Begin saving locale files");

            // Go through each locale
            for (Entry<Locale, File> entry : filePerLocale.entrySet()) {
                Map<String, String> messages = messagesPerLocale.get(entry.getKey());

                try (PrintWriter printWriter = new PrintWriter(entry.getValue(),
                        CharsetTools.UTF_8.toString())) {

                    // Save the known used (sorted) at the top
                    for (String code : knownUsedCodes.stream().sorted(String.CASE_INSENSITIVE_ORDER)
                            .collect(Collectors.toList())) {
                        printWriter.println(code + "=" + messages.get(code));
                    }
                    printWriter.println();

                    // Save the others (sorted) at the bottom
                    Set<String> unknownCodes = new HashSet<>();
                    unknownCodes.addAll(messages.keySet());
                    unknownCodes.removeAll(knownUsedCodes);
                    if (!unknownCodes.isEmpty()) {
                        printWriter.println("# Unknown");
                        printWriter.println();

                        for (String code : unknownCodes.stream().sorted(String.CASE_INSENSITIVE_ORDER)
                                .collect(Collectors.toList())) {
                            printWriter.println(code + "=" + messages.get(code));
                        }
                        printWriter.println();
                    }
                } catch (Exception e) {
                    logger.error("Could not write the file", e);
                }
            }

            // Save the known
            FileTools.writeFile(Joiner.on('\n').join(
                    knownUsedCodes.stream().sorted(String.CASE_INSENSITIVE_ORDER).collect(Collectors.toList())),
                    tmpUsed);

            logger.info("Done saving locale files");
        }

    }) //
            .setDelayAfterLastTriggerMs(5000) //
            .setMaxDelayAfterFirstRequestMs(10000) //
            .setFirstPassThrough(true) //
            .start();

    smoothTrigger.request();
}

From source file:com.util.FileService.java

/**
 * Get case file location/* ww  w. j ava 2 s  .co  m*/
 * 
 * @param item RelatedCaseModel
 * @return String file path
 */
public static String getCaseFolderLocationEmailOutRelatedCase(EmailOutRelatedCaseModel item) {
    return Global.getActivityPath() + File.separatorChar + NumberFormatService.getSection(item.getCaseType())
            + File.separatorChar + item.getCaseYear() + File.separatorChar
            + NumberFormatService.FullCaseNumber(item) + File.separatorChar;
}

From source file:de.lazyzero.kkMulticopterFlashTool.utils.Zip.java

public static void unzip2folder(File zipFile, File toFolder) throws FileExistsException {
    if (!toFolder.exists()) {
        toFolder.mkdirs();//ww w .  j  a  va  2 s  . co m
    } else if (toFolder.isFile()) {
        throw new FileExistsException(toFolder.getName());
    }

    try {
        ZipEntry entry;
        @SuppressWarnings("resource")
        ZipFile zipfile = new ZipFile(zipFile);
        Enumeration<? extends ZipEntry> e = zipfile.entries();
        while (e.hasMoreElements()) {
            entry = e.nextElement();

            //            String newDir;
            //            if (entry.getName().indexOf("/") == -1) {
            //               newDir = zipFile.getName().substring(0, zipFile.getName().indexOf("."));
            //            } else {
            //               newDir = entry.getName().substring(0, entry.getName().indexOf("/"));
            //            }
            //            String folder = toFolder + (File.separatorChar+"") + newDir;
            //            System.out.println(folder);
            //            if ((new File(folder).mkdir())) {
            //               System.out.println("Done.");
            //            }
            System.out.println("Extracting: " + entry);
            if (entry.isDirectory()) {
                new File(toFolder + (File.separatorChar + "") + entry.getName()).mkdir();
            } else {
                BufferedInputStream is = new BufferedInputStream(zipfile.getInputStream(entry));
                int count;
                byte data[] = new byte[2048];
                String fileName = toFolder + (File.separatorChar + "") + entry.getName();
                FileOutputStream fos = new FileOutputStream(fileName);
                BufferedOutputStream dest = new BufferedOutputStream(fos, 2048);
                while ((count = is.read(data, 0, 2048)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.flush();
                dest.close();
                is.close();
                System.out.println("extracted to: " + fileName);
            }

        }
    } catch (ZipException e1) {
        zipFile.delete();
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } finally {

    }

}

From source file:gov.nih.nci.ncicb.cadsr.bulkloader.CaDSRBulkLoadProcessor.java

private File createOutputFile(File inputFile, String outputDir) throws Exception {
    File outputDirFile = new File(outputDir);
    outputDirFile.mkdirs();// w ww .ja  v a  2  s  . c  o  m

    String opFilePath = outputDirFile.getAbsolutePath() + File.separatorChar + inputFile.getName();
    File opFile = new File(opFilePath);
    if (!opFile.exists()) {
        boolean opFileCreated = opFile.createNewFile();
        if (!opFileCreated) {
            throw new RuntimeException(
                    "Error writing to dir [" + outputDir + "]. Please make sure this dir is writable");
        }
    }
    return opFile;
}

From source file:org.bndtools.rt.repository.server.RepositoryResourceComponent.java

@GET
@Path("bundles/{bsn}/{version}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getBundleByBsnAndVersion(@PathParam("bsn") String bsn, @PathParam("version") String versionStr)
        throws Exception {
    ResourceHandle handle = repo.getHandle(bsn, versionStr, Strategy.EXACT, null);
    if (handle == null)
        return Response.status(Status.NOT_FOUND).build();

    UriBuilder uriBuilder = UriBuilder.fromResource(RepositoryResourceComponent.class).path("{bundlePath}");

    if (handle.getLocation() == Location.local) {
        String bundlePath = handle.request().getCanonicalPath();
        String prefix = storageDir.getAbsolutePath() + File.separatorChar;
        if (bundlePath.startsWith(prefix)) {
            bundlePath = bundlePath.substring(prefix.length());
            URI bundleUri = uriBuilder.build(bundlePath);

            return Response.seeOther(bundleUri).build();
        }// w w w  .j  ava 2  s  .  co m
    }
    return Response.serverError().entity("Bundle is not available in the repository storage area").build();
}

From source file:com.stratelia.silverpeas.versioningPeas.servlets.DragAndDrop.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    SilverTrace.info("versioningPeas", "DragAndDrop.doPost", "root.MSG_GEN_ENTER_METHOD");
    if (!FileUploadUtil.isRequestMultipart(req)) {
        res.getOutputStream().println("SUCCESS");
        return;//from  ww  w.  jav  a  2s. c  o  m
    }
    try {
        req.setCharacterEncoding("UTF-8");
        String componentId = req.getParameter("ComponentId");
        SilverTrace.info("versioningPeas", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                "componentId = " + componentId);
        String id = req.getParameter("Id");
        SilverTrace.info("versioningPeas", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "id = " + id);
        int userId = Integer.parseInt(req.getParameter("UserId"));
        SilverTrace.info("versioningPeas", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                "userId = " + userId);
        int versionType = Integer.parseInt(req.getParameter("Type"));
        boolean bIndexIt = StringUtil.getBooleanValue(req.getParameter("IndexIt"));

        String documentId = req.getParameter("DocumentId");

        List<FileItem> items = FileUploadUtil.parseRequest(req);

        VersioningImportExport vie = new VersioningImportExport();
        int majorNumber = 0;
        int minorNumber = 0;

        String fullFileName = null;
        for (FileItem item : items) {
            if (!item.isFormField()) {
                String fileName = item.getName();
                if (fileName != null) {
                    fileName = fileName.replace('\\', File.separatorChar);
                    fileName = fileName.replace('/', File.separatorChar);
                    SilverTrace.info("versioningPeas", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                            "file = " + fileName);
                    long size = item.getSize();
                    SilverTrace.info("versioningPeas", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                            "item #" + fullFileName + " size = " + size);
                    String mimeType = AttachmentController.getMimeType(fileName);
                    String physicalName = saveFileOnDisk(item, componentId, vie);
                    DocumentPK documentPK = new DocumentPK(-1, componentId);
                    if (StringUtil.isDefined(documentId)) {
                        documentPK.setId(documentId);
                    }
                    DocumentVersionPK versionPK = new DocumentVersionPK(-1, documentPK);
                    ForeignPK foreignPK = new ForeignPK(id, componentId);
                    Document document = new Document(documentPK, foreignPK, fileName, null,
                            Document.STATUS_CHECKINED, userId, null, null, componentId, null, null, 0, 0);

                    DocumentVersion version = new DocumentVersion(versionPK, documentPK, majorNumber,
                            minorNumber, userId, new Date(), null, versionType,
                            DocumentVersion.STATUS_VALIDATION_NOT_REQ, physicalName, fileName, mimeType,
                            new Long(size).intValue(), componentId);

                    List<DocumentVersion> versions = new ArrayList<DocumentVersion>();
                    versions.add(version);
                    VersionsType versionsType = new VersionsType();
                    versionsType.setListVersions(versions);
                    document.setVersionsType(versionsType);
                    List<Document> documents = new ArrayList<Document>();
                    documents.add(document);

                    try {
                        vie.importDocuments(foreignPK, documents, userId, bIndexIt);
                    } catch (Exception e) {
                        // storing data into DB failed, delete file just added on disk
                        deleteFileOnDisk(physicalName, componentId, vie);
                        throw e;
                    }
                } else {
                    SilverTrace.info("versioningPeas", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                            "item " + item.getFieldName() + "=" + item.getString());
                }
            }
        }
    } catch (Exception e) {
        SilverTrace.error("versioningPeas", "DragAndDrop.doPost", "ERREUR", e);
        res.getOutputStream().println("ERROR");
        return;
    }
    res.getOutputStream().println("SUCCESS");
}

From source file:com.stimulus.archiva.store.MessageStore.java

protected File getFileFromHashValue(Volume volume, String hash, String extension) {
    String filename = volume.getPath() + File.separatorChar + hash.substring(0, 3) + File.separator
            + hash.substring(3, 6) + File.separator + hash + extension;
    logger.debug("getMessageFileName() { return='" + filename + "'");
    return new File(filename);
}

From source file:com.googlecode.jgenhtml.JGenHtmlTestUtils.java

/**
 * Helper for getTraceFiles methods.//from ww  w .  ja v a2 s . co  m
 * Will prepend the test dir path to the names and ensure these files exist in the test dir.
 * @param traceFiles An array of dummy traceFile names.
 */
private static void addPathAndEnsureExists(final String[] traceFiles) {
    File dir = getTestDir();
    for (int i = 0; i < traceFiles.length; i++)//append the full path to the file names and make sure they actually exist
    {
        String name = traceFiles[i];
        traceFiles[i] = dir.getAbsolutePath() + File.separatorChar + name;
        File datFile = new File(traceFiles[i]);
        if (!datFile.exists()) {
            JGenHtmlUtils.writeResource(name, dir);
        }
    }
}

From source file:gov.nih.nci.sdk.example.generator.CXFSpringConfGenerator.java

private void generateSpringWebConf(StringTemplateGroup group) {
    StringTemplate template = group.getInstanceOf("SpringWeb");
    String outputDir = getScriptContext().getProperties().getProperty("PROJECT_ROOT") + File.separatorChar
            + "webapp" + File.separatorChar + "WEB-INF";
    GeneratorUtil.writeFile(outputDir, "web.xml", template.toString());
}