List of usage examples for java.io File toPath
public Path toPath()
From source file:name.npetrovski.jphar.DataEntry.java
/** * Create entry from file/*from w ww . j a v a 2s.co m*/ * */ public static DataEntry createFromFile(File file, Compression.Type compression) throws IOException { EntryManifest em = new EntryManifest(); em.setCompression(new Compression(compression)); em.setTimestamp((int) file.lastModified() / 1000); em.getPath().setName(file.toPath().toString().replace("\\", "/")); DataEntry entry = new DataEntry(em); entry.setSource(file.getCanonicalFile()); if (file.isDirectory()) { em.getCompression().setType(Compression.Type.NONE); } else { byte[] data = Files.readAllBytes(file.toPath()); CRC32 crc = new CRC32(); crc.update(data); em.setCRC32((int) crc.getValue()); em.setUncompressedSize(data.length); } return entry; }
From source file:com.epam.catgenome.controller.util.MultipartFileSender.java
public static MultipartFileSender fromFile(File file) { return new MultipartFileSender().setFilepath(file.toPath()); }
From source file:com.machinepublishers.jbrowserdriver.ResponseHandler.java
private static void writeContentToDisk(byte[] content, File dir, String url, String contentType, String contentDisposition) { String filename = Util.randomFileName(); File contentFile = new File(dir, new StringBuilder().append(filename).append(".content").toString()); File metaFile = new File(dir, new StringBuilder().append(filename).append(".metadata").toString()); contentFile.deleteOnExit();//w w w. ja va 2 s .co m metaFile.deleteOnExit(); try { Files.write(contentFile.toPath(), content); Files.write(metaFile.toPath(), (new StringBuilder().append(StringUtils.isEmpty(url) ? "" : url).append("\n") .append(StringUtils.isEmpty(contentType) ? "" : contentType).append("\n") .append(StringUtils.isEmpty(contentDisposition) ? "" : contentDisposition).toString()) .getBytes("utf-8")); } catch (Throwable t) { } }
From source file:com.simiacryptus.util.lang.CodeUtil.java
/** * Gets heapCopy text./*from www .j a va 2s. co m*/ * * @param callingFrame the calling frame * @return the heapCopy text * @throws IOException the io exception */ public static String getInnerText(@javax.annotation.Nonnull final StackTraceElement callingFrame) throws IOException { try { @javax.annotation.Nonnull final File file = com.simiacryptus.util.lang.CodeUtil.findFile(callingFrame); assert null != file; final int start = callingFrame.getLineNumber() - 1; final List<String> allLines = Files.readAllLines(file.toPath()); final String txt = allLines.get(start); @javax.annotation.Nonnull final String indent = com.simiacryptus.util.lang.CodeUtil.getIndent(txt); @javax.annotation.Nonnull final ArrayList<String> lines = new ArrayList<>(); for (int i = start + 1; i < allLines.size() && (com.simiacryptus.util.lang.CodeUtil.getIndent(allLines.get(i)).length() > indent.length() || allLines.get(i).trim().isEmpty()); i++) { final String line = allLines.get(i); lines.add(line.substring(Math.min(indent.length(), line.length()))); } return lines.stream().collect(Collectors.joining("\n")); } catch (@javax.annotation.Nonnull final Throwable e) { return ""; } }
From source file:com.spotify.helios.cli.CliConfig.java
/** * Returns a CliConfig instance with values parsed from the specified file. * * If the file is not found, a CliConfig with pre-defined values will be returned. * * @param defaultsFile The file to parse from * @throws IOException If the file exists but could not be read * @throws URISyntaxException If a HELIOS_MASTER env var is present and doesn't parse as a URI *///from w w w .j a va2 s. co m public static CliConfig fromFile(File defaultsFile) throws IOException, URISyntaxException { final Map<String, Object> config; // TODO: use typesafe config for config file parsing if (defaultsFile.exists() && defaultsFile.canRead()) { config = Json.read(Files.readAllBytes(defaultsFile.toPath()), OBJECT_TYPE); } else { config = ImmutableMap.of(); } return fromEnvVar(config); }
From source file:de.fatalix.book.importer.BookMigrator.java
private static void exportBatchWise(SolrServer server, File exportFolder, int batchSize, int offset, Gson gson) throws SolrServerException, IOException { QueryResponse response = SolrHandler.searchSolrIndex(server, "*:*", batchSize, offset); List<BookEntry> bookEntries = response.getBeans(BookEntry.class); System.out.println(/*from ww w . j a va2 s .c om*/ "Retrieved " + (bookEntries.size() + offset) + " of " + response.getResults().getNumFound()); for (BookEntry bookEntry : bookEntries) { String bookTitle = bookEntry.getTitle(); bookTitle = bookTitle.replaceAll(":", " "); File bookFolder = new File(exportFolder, bookEntry.getAuthor() + "-" + bookTitle); bookFolder.mkdirs(); if (bookEntry.getCover() != null) { if (bookEntry.getEpub() != null) { File bookData = new File(bookFolder, bookEntry.getAuthor() + "-" + bookTitle + ".epub"); Files.write(bookData.toPath(), bookEntry.getMobi(), StandardOpenOption.CREATE_NEW); } if (bookEntry.getMobi() != null) { File bookData = new File(bookFolder, bookEntry.getAuthor() + "-" + bookTitle + ".mobi"); Files.write(bookData.toPath(), bookEntry.getMobi(), StandardOpenOption.CREATE_NEW); } File coverData = new File(bookFolder, bookEntry.getAuthor() + "-" + bookTitle + ".jpg"); Files.write(coverData.toPath(), bookEntry.getCover(), StandardOpenOption.CREATE_NEW); File metaDataFile = new File(bookFolder, bookEntry.getAuthor() + "-" + bookTitle + ".json"); BookMetaData metaData = new BookMetaData(bookEntry.getAuthor(), bookEntry.getTitle(), bookEntry.getIsbn(), bookEntry.getPublisher(), bookEntry.getDescription(), bookEntry.getLanguage(), bookEntry.getReleaseDate(), bookEntry.getMimeType(), bookEntry.getUploadDate(), bookEntry.getViewed(), bookEntry.getShared()); gson.toJson(metaData); Files.write(metaDataFile.toPath(), gson.toJson(metaData).getBytes(), StandardOpenOption.CREATE_NEW); } } if (response.getResults().getNumFound() > offset) { exportBatchWise(server, exportFolder, batchSize, offset + batchSize, gson); } }
From source file:nc.noumea.mairie.appock.core.utility.AppockUtil.java
/** * Lit le contenu d'un fichier, et le convertit en base 64 * @param file fichier//from ww w .j a v a 2 s . c om * @return contenu base 64 * @throws IOException exception */ public static String readFileToBase64(File file) throws IOException { byte[] bytes; bytes = Files.readAllBytes(file.toPath()); StringBuilder sb = new StringBuilder(); sb.append("data:" + getMimeType(bytes) + ";base64,"); sb.append(org.apache.commons.codec.binary.StringUtils.newStringUtf8(Base64.encodeBase64(bytes, false))); return sb.toString(); }
From source file:com.schnobosoft.semeval.cortical.Util.java
/** * Read a file that contains one score per line, as a SemEval gold {@code .gs} file. Empty lines * are allowed and are read as missing values. * * @param scoresFile the scores file to read * @return a list of optional double values of the same length as the input file. For an empty * line, a {@link Optional#EMPTY} object is added to the output list. * @throws IOException/* ww w . j av a 2s .com*/ */ public static List<Optional> readScoresFile(File scoresFile) throws IOException { if (!scoresFile.getName().startsWith(GS_FILE_PREFIX)) { throw new IllegalArgumentException(scoresFile + " does not match expected pattern."); } LOG.info("Reading scores file " + scoresFile); return Files.lines(scoresFile.toPath()) .map(line -> line.isEmpty() ? Optional.empty() : Optional.of(Double.valueOf(line))) .collect(Collectors.toList()); }
From source file:de.fatalix.book.importer.BookMigrator.java
private static BookEntry importBatchWise(File bookFolder, Gson gson) throws IOException { BookEntry bookEntry = new BookEntry(); for (File file : bookFolder.listFiles()) { if (file.getName().contains(".mobi")) { byte[] bookData = Files.readAllBytes(file.toPath()); bookEntry.setMobi(bookData); } else if (file.getName().contains(".jpg")) { byte[] coverData = Files.readAllBytes(file.toPath()); bookEntry.setCover(coverData); } else if (file.getName().contains(".epub")) { byte[] bookData = Files.readAllBytes(file.toPath()); bookEntry.setEpub(bookData); } else if (file.getName().contains(".json")) { BookMetaData bmd = gson.fromJson( IOUtils.toString(new FileInputStream(file), Charset.defaultCharset()), BookMetaData.class); bookEntry.setAuthor(bmd.getAuthor()).setTitle(bmd.getTitle()).setIsbn(bmd.getIsbn()) .setPublisher(bmd.getPublisher()).setDescription(bmd.getDescription()) .setLanguage(bmd.getLanguage()).setMimeType(bmd.getMimeType()) .setUploadDate(bmd.getUploadDate()).setReleaseDate(bmd.getReleaseDate()); } else if (file.getName().contains(".opf")) { bookEntry = parseOPF(file, bookEntry); bookEntry.setMimeType("mobi").setUploadDate(new DateTime(DateTimeZone.UTC).toDate()); }/*from ww w .jav a 2s . co m*/ } return bookEntry; }
From source file:de.teamgrit.grit.report.TexGenerator.java
/** * This method creates a TeX file from a Submission instance. * /*from ww w . j ava 2 s .c o m*/ * @param submission * A SubmissionObj containing the information that the content * gets generated from. * @param outdir * the output directory * @param courseName * the name of the course the exercise belongs to * @param exerciseName * the name of the exercise * @return The Path to the created TeX file. * @throws IOException * If something goes wrong when writing. */ public static Path generateTex(final Submission submission, final Path outdir, final String courseName, final String exerciseName) throws IOException { final File location = outdir.toFile(); File file = new File(location, submission.getStudent().getName() + ".report.tex"); if (Files.exists(file.toPath())) { Files.delete(file.toPath()); } file.createNewFile(); writePreamble(file); writeHeader(file, submission, courseName, exerciseName); writeOverview(file, submission); writeTestResult(file, submission); // if there are compile errors, put these in the .tex file instead of // JUnit Test result CheckingResult checkingResult = submission.getCheckingResult(); if (!(checkingResult.getCompilerOutput().isCleanCompile())) { writeCompilerErrors(file, submission); } else { TestOutput testResults = checkingResult.getTestResults(); if ((testResults.getPassedTestCount() < testResults.getTestCount()) && testResults.getDidTest()) { writeFailedTests(file, submission); } } writeCompilerOutput(file, submission); writeSourceCode(file, submission); writeClosing(file); return file.toPath(); }